Skip to content Skip to sidebar Skip to footer

Setattribute() Doesn't Work The Way I Expect It To

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 w

Solution 1:

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");
<divid="01"><inputtype="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.

Solution 2:

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/

Solution 3:

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

Post a Comment for "Setattribute() Doesn't Work The Way I Expect It To"