Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's val() method change doesn't seem to change the DOM

Doing $("#someId").val("newValue") doesn't change the DOM -- I can retrieve this value with $("#someId").val(), but the element in the DOM still doesn't have a value attribute.

How do I set the value of an input component and also change the DOM?

I'm using jQuery 1.5.1.

like image 377
Alex Ivasyuv Avatar asked Mar 08 '11 12:03

Alex Ivasyuv


4 Answers

.val() does change the DOM. For example this:

$("#someId").val("newValue");

alert(document.getElementById('someId').value);

alerts 'newValue'.

See DEMO.

If you want to change the default value to be used in form resets, try this:

$("#someId").attr("defaultValue", "newValue");

See DEMO.

like image 136
rsp Avatar answered Nov 02 '22 18:11

rsp


This

$("#someId").val("newValue")

will change the value of the input element.

This

$("#someId").attr("value","newValue")

will change the value of the value attribute.

The second may help if you want to write the element. So, for example:

$("#someId").val("newValue")
$("#someId").attr("value","newValue")
write($("#someId").parent())

-will result in the new value being rendered, whereas

$("#someId").val("newValue")
write($("#someId").parent())

-will just show the original value.

like image 44
Bryn Lewis Avatar answered Nov 02 '22 18:11

Bryn Lewis


Answer if you are using the firebug, there is a bug in it about updating the dom, you must click the window object to refresh it :)

Explanation @alex i was reading comments below. on @rsp answer and you seem to confuse the dom with the html tree a dom, is a tree like list of values used to keep track of values. and yes click dom tab, or right click the element in question and then inspect it in dom, values, changes dont show up on firebug, because of security reasons that prevent anything other than a browser to change its values or possibly because fire bug, has got it wrong and they probably working on it :)

like image 2
Val Avatar answered Nov 02 '22 16:11

Val


Reading from "rsp" answer and discussion:

you want to change the HTML source, not the DOM.

Therefore use:

$('#YOUR_ID option[value="YOUR_VALUE"]').attr('selected', 'selected');

The method .val() does not change the HTML source.

Cheers. Stefano

like image 1
Stefano Vespucci Avatar answered Nov 02 '22 16:11

Stefano Vespucci