With jQuery it is very easy to change the value of a form element, here’s a quick example that changes the text for a form element with id=’input1′
$('#input1').val('this is the new value');
On the page you will see your input change as requested. If you look at the value with jQuery there are no surprises.
console.log($(#input1).val());
//will output 'this is a new value'
However you may be surprised that it hasn’t been changed if you try to look at it with jQuery in a different way. Assuming that input1 is contained in a div with id ‘div1’.
console.log($('#div1').html());
You will see this
The DOM doesn’t look like it has been updated. This certainly wasn’t the behaviour I expected from this so it took a lot of digging to find out what was going on.
It turns out that the HTML value attribute isn’t necessarily the value that is displayed on the page, instead it is known as the default value – used when the page is first loaded or if the form is reset.
The solution. If you want to update the value that appears on the page and the value that’s retrievable by the .html() method is this:
$('#input1').val('this is the new value');
//before jQuery 1.6
$('#input1').attr('defaultValue', 'this is the new value');
//after jQuery 1.5.2
$('#input1').attr('value', 'this is the new value');
Set the ‘defaultValue’ or ‘value’ attribute depending on your version of jQuery as well as using the .val() method. You’ll find that getting the html with jQuery will now show the correct value.
Thanks very much. This article really helped me out a deep and intricate web-like situation. I also need extra help for the <select> element to update the selected=”selected” attribute when changed. Thanks as I expect further clarification.
if($(this).val() == $(this).attr(‘defaultValue’)) {
$(this).val(”);
};
attr not working… what is the problem?
Thank you@
Wow, Saved my day
Thank you so much!
I’vent found what’s going on.
Thank you.
Thanks its really working 🙂
GREAT discovery! I wish someone could explain, though, why one has to use both attr() and val() functions (one would think that one function would set both the value attribute as well as the HTML display). But, Mr. Willis-Owen, thanks again!
Great article!! It really helped me i’ve lost hours and hours trying to debug my code and the solution was here 🙂
I’m surprised that this is not mentionned in the official jQuery documentation.