Here's a confusing question. I need to replace an <input> with a different <input> but I need to preserve the onclick attribute. Here's an example:
<input type="image" class="previous_page_img graybutton mediumbutton" src="btn_prevpage.png" onclick="Add_Search_Param('page', 1); Refine();" alt="">
Since I cannot change the <input> type to a button, I want to replace it with a button, however, I need to preserve the "onclick" attribute. So first, I'd have to break up the element. Replace it with a button and append the original onclick attribute to the new button.
So in the end, I'd have this onclick="Add_Search_Param('page', 1); Refine();" added to the new button. Since the onclick changes, a simple .attr or .prop function would not be sufficient. It must clone the onclick attribute. Can anyone help me? Thanks.
Here's jsFiddle that does not preserve the onclick attribute but does everything else: http://jsfiddle.net/rAMcw/
You could do (i used a simple javascript function to test it)
<input type="image" class="previous_page_img graybutton mediumbutton" src="btn_prevpage.png" onclick="Add_Search_Param('page', 1); Refine();" alt="">
var onclick = $('.mediumbutton').attr('onclick');
var but = $('<input/>', { type: "button", value: "pressme", onclick: onclick});
$('.mediumbutton').replaceWith(but);
fiddle here http://jsfiddle.net/KjBm3/
Just create a new button right after the input, set the input to display: none; (or jQuery('#input').hide()) and have the button onclick trigger the input's onclick (jQuery('#button').click(function(){ jQuery('#input').trigger('click'); });
How about cloning?
var x = $('input').clone(true);
x.attr('type','button').addClass('previous_page_img graybutton mediumbutton').val('Previous Page');
$('input').replaceWith(x);
Updated jsFiddle
What is wrong with turning the existing input element into a button?
$("input.previous_page_img").prop("type", "button").val("Previous Page");
jQuery 1.4.2: (set the property in plain-old JavaScript);
$("input.previous_page_img").val("Previous Page")[0].type = "button";
Demo
Related
I am trying to remove the user input and replace it with the original placeholder by using the empty() function.
Here is the jQuery file which takes input from user through a <form> and appends it to list with the template() structure:
var template = function(text) {
return '<p><input type="checkbox"><i class="glyphicon glyphicon-star"></i><span>' + text + '</span><i class="glyphicon glyphicon-remove"></i></p>';
};
var main = function() {
$('.form').submit(function() {
var text = $('#todo').val();
var html = template(text);
$('.list').append(html);
$('#todo').empty();
return false;
});
};
$(document).ready(main);
After the user submits their text and it is added to the list I want the 'form' input to empty so you can enter a new item with out deleting what you just typed.
Here is a snippet of the html file that jQuery is interacting with:
<form class="form">
<div class="form-container">
<input id="todo" type="text" class="form-input" placeholder="Add item">
</div>
<button type="submit" class="btn">+</button>
</form>
Why is the line
$('#todo').empty();
not removing the user input and returning it to the original placeholder?
The empty method doesn't delete the attributes or values but it removes the html inside an element. You should use val:
$('#todo').val('');//To empty the value
If you want to remove the placeholder too then use removeAttr method:
$('#todo').removeAttr('placeholder');
.empty() is for other use cases. From the docs...
Remove all child nodes of the set of matched elements from the DOM.
Instead, you can .val('') your <input />. Observe the following simplified example...
$('.form').submit(function() {
$('#todo').val('');
return false;
});
JSFiddle Link - demo
as an observation to your neighboring code you can also pass the event and call .preventDefault() in place of return false;. Alternatively, you can call reset() in your function block as such: this.reset() - reset demo with default behavior prevented.
Try this:
$('form').trigger("reset");
This is the most elegant and correct way since it will work when you have multiple and different type of inputs without needing to do any changes. Much better than trying to empty and resetting placehorders on all fields. This will make sure to set the fields to initial state (having placeholders set too).
Based on your code you could do:
$('.form').submit(function() {
// ...
$(this).trigger("reset");
// ...
});
See it working on an example form based on yours with more fields inputs and select here.
See JQuery reset Doc here: JQuery API Doc/reset
So I am trying to add an onClick attribute to a button created with Javascript. Obviously I am using Javascript to add it, however it won't go through because when I inspect the element on the web page it doesn't show an onClick attribute there. This is the code I have to create the button
var buttonExponent = document.createElement('button');
buttonExponent.innerHTML = '^';
buttonExponent.onclick = function(){appendExpr(this.className);}; <---This is my problem
buttonExponent.className = 'button operator ' + expression.id + ' top';
buttonExponent.style.marginTop = '0px';
buttonExponent.style.marginLeft = '-6px';
container.appendChild(buttonExponent);
The rest of the functions work fine and everything, however the onClick attribute simply won't get added on. I have tried doing it multiple ways, but none of them work
EDIT: Figured I should add what the output is on the webpage, the element has this HTML
<button class="button operator expr1 top" style="margin-top: 0px; margin-left: -6px;">^</button>
When it should be looking like this
<button onClick="appendExpr(this.className);" class="button operator expr1 top" style="margin-top: 0px; margin-left: -6px;">^</button>
Modifying the element.onclick DOM property doesn't modify the element's onclick attribute. They are two separate pieces of data, confusingly.
To set the attribute, use element.setAttribute('onclick','code here').
Nvm, the problem was that by setting the onClick through element.onClick I was setting the property without the attribute, and the properties don't show up when inspecting the element on the webpage, so I had to set the attribute for it to show up
window.onload = function() {
try{
document.getElementById('result').focus();
}catch(err){
}
}
In my form div result id load when form submits and when it show i want to focus on it.
the above code is not working in my case.
Please help me to find problem with this code.
jsfiddle
According to your jsFiddle, #result is a div. You can't really focus on a div the way you can with a form element or link, but you can jump to that part of the page using the following javascript instead:
window.location.hash = '#result';
You can not focus to a div element. But you can use
window.location.hash = '#result';
to scroll to div#result element
Here's a working jsFiddle.
1. Give the div a tab index of 0 (meaning it is ordered first):
<div class="result" tabindex="0" id="result">
(Find out more about the tabindex property here.)
2. Remove your <script> tags:
window.onload = function() {
try{
document.getElementById('result').focus();
}catch(err){
}
}
3. Use no wrap in <head> instead of onload.
You are trying to focus on a div, which by default can not be put to focus using script. To do that you need to set the tabindex attribute of the result div. You need to add the attribute tabindex and set its value to 0 and then your function document.getElementById().focus() will work
Also in your fiddle is not allowed inside javascript block. Try this fiddle
I have a button script to change the buttons in a frame based on the page loaded in the main frame. The problem I'm experiencing is that while the background images, tabindex and text on the button (innerHTML) all change as expected, the onclick doesn't. It appears to completely ignore it. Here's the script I'm using:
function createbutton(btn_N, btn_I, btn_L, btn_D) // (Div Name, Tab Index, Button Text, Page To Load){
var btnN = top.frames['buttonbar'].document.getElementById(btn_N);
btnN.style.cssText = "display:block; cursor:pointer; padding-left:16px; padding-top:5px;";
btnN.onmouseover = function() {this.style.backgroundImage = "url('./osdimages/navBG_roll.png')";};
btnN.onmouseout = function() {this.style.backgroundImage = '';};
btnN.tabindex = btn_I;
btnN.innerHTML = btn_L;
btnN.onclick = btn_D;
}
The button call looks like this:
createbutton("button01", 1, "New Order/Browse", "parent.frames['content'].location.href='createorder/createorder.asp';");
There is a difference between attributes and properties.
The best example of this is as follows:
HTML: <input type="text" value="hello" id="test" />
Type something in the text box
document.getElementById('test').value is whatever you typed
document.getElementById('test').getAttribute("value") is whatever was in the HTML
Some attributes are directly mapped to properties and vice versa, but this is not always the case.
For instance, the onClick attribute takes a string that is then eval'd, but the onclick property takes a function. This is why your code isn't working.
Either pass a valid function, or use setAttribute.
You are setting onclick with a string, it needs a function to execute.
createbutton("button01", 1, "New Order/Browse", function(){ parent.frames['content'].location.href='createorder/createorder.asp'; });
My code is as follows:
<script>
$(document).ready(function() {
var tagCounter=0;
$("#tag-add-button").click(function () {
var text = $("#tagadd").val();
$("#set-tags").append("<input type='text' id='tag"+tagCounter+"' READONLY>");
$("#tag"+tagCounter).val(text);
$("#tagadd").val("");
tagCounter++;
});
});
</script>
This does the following:
When tag-add-button is clicked, it takes the text from the inputbox (tagadd) and puts it in a new inputbox thats appended to the set-tags div. The tagadd inputbox is then made blank.
The problem I'm having, is I want each input box to have its own remove button. But I don't see how the javascript can be generated for that when there can be an unlimited number of input boxes...
Any ideas?
Put the input element inside of a div or span, and make the remove button a sibling of the input element. Then, in the onclick handler of the button, just do something like $(this).parent().remove()
This has the effect of removing both the input element, and the remove button itself
Rather than using an id (#tag-add-button), use classes and then use the each function of jQuery and traverse to the appropriate elements.
$(document).ready(function() {
var tagCounter=0;
$("#tag-add-button").click(function () {
var text = $("#tagadd").val();
$("#set-tags").append('<input type="text" id="tag'+tagCounter+'" READONLY /><span class="remove">Remove</span>');
$("#tag"+tagCounter).val(text);
$("#tagadd").val("");
tagCounter++;
});
$('span.remove').bind('click',function(){
$(this).prev('input').andSelf().remove();
});
});