jQuery changing form values not affecting the DOM

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.

6 Replies to “jQuery changing form values not affecting the DOM”

  1. 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.

  2. if($(this).val() == $(this).attr(‘defaultValue’)) {
    $(this).val(”);
    };

    attr not working… what is the problem?
    Thank you@

  3. 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!

Leave a Reply to Peter Robot Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.