Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setAttribute() doesn't work the way I expect it to [duplicate]

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?

like image 686
Zahra Avatar asked Apr 28 '15 20:04

Zahra


3 Answers

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.

like image 118
dfsq Avatar answered Oct 23 '22 03:10

dfsq


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/

like image 37
Trott Avatar answered Oct 23 '22 01:10

Trott


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")
like image 22
mohamed-ibrahim Avatar answered Oct 23 '22 02:10

mohamed-ibrahim