jQuery's val() method change doesn't seem

2020-04-05 08:59发布

问题:

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.

回答1:

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



回答2:

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 :)



回答3:

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.



回答4:

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