this line of code:
document.getElementById('01').getElementsByTagName("input")[0].setAttribute("value", "1");
works perfectly fine when "input" doesn't already have a value. but when the input already has a value, it wouldn't change the value. why is that?
Sounds like you faced a confusing difference between element property value
and value
attribute. Those are not the same things.
The thing is that value-attribute serves the purpose of the default value, so if the element already has a property value then changing value-attribute will not be reflected in UI.
Documentation says this:
Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val).
So to demonstrate this situation consider this little demo:
document.getElementById("01").getElementsByTagName("input")[0].value = 'property set';
document.getElementById("01").getElementsByTagName("input")[0].setAttribute("value", "two");
<div id="01">
<input type="text" />
</div>
In the above snippet the value attribute is indeed updated to value two
and you can verify it if you try to read it back with getAttribute('value')
, however the value-property takes precedence over attribute, so later is not rendered.
That JavaScript absolutely does change the value of the <input>
tag when the tag already has a value
attribute. See for yourself here: http://jsfiddle.net/qg7d4m32/
for input field if you want to set a value just use value
Pure javascript:
document.getElementById('01').getElementsByTagName("input")[0].value = "value"
jQuery:
$("input").val("value")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With