jQuery changing form values not affecting the DOM

By | April 28, 2012

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

<input id="input1" type="text" name="input1" value="original value" />

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.

2 thoughts on “jQuery changing form values not affecting the DOM

  1. Peter Robot

    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.

    Reply
  2. red

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

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

    Reply

Leave a Reply

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


7 − = 2