开发者

Unexpected result of document.getElementById.value?

开发者 https://www.devze.com 2023-02-13 23:29 出处:网络
When I run the following code: document.getElementById(\'somevar\').value = \'25\'; alert(document.getElementById(\'somevar\').value );

When I run the following code:

document.getElementById('somevar').value = '25';
alert(document.getElementById('somevar').value );
开发者_Python百科

"somevar" is displayed, instead of 25. Why is this? Thanks in advance for any help.

EDIT: input type of 'somevar'is hidden


I suspect this is happening because when you run the code the element you're trying to access is not yet ready. Make sure you run your code after the DOM has loaded by using onload for plain javascript or the ready event if using jQuery.


As show on my fiddle, if an element is defined with the right name, it show the correct result:

http://jsfiddle.net/Achilleterzo/kcp2n/


It should work. Here is a sample on JsFiddle

0

精彩评论

暂无评论...
验证码 换一张
取 消