I have a text box element whose value I am trying to access using document.getElementById(\"id-name\").value
. I find that the call is returning a null instead o
This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):
var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false
and changing the console.log
to alert
, I still get the desired output in IE6.
It seems that you've omitted the value attribute in HTML markup.
Add it there as <input value="" ... >
.
For your code
var mytextvalue = document.getElementById("mytext");
mytextvalue
will contain null
if you have a document.write()
statement before this code. So remove the document.write
statement and you should get a proper text object in the variable mytextvalue
.
This is caused by document.write
changing the document.
try this...
<script type="text/javascript">
function test(){
var av=document.getElementById("mytext").value;
alert(av);
}
</script>
<input type="text" value="" id="mytext">
<input type="button" onclick="test()" value="go" />
fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.
Please check this fiddle and let me know if you get an alert of null value. I have copied your code there and added a couple of alerts. Just like others, I also dont see a null being returned, I get an empty string. Which browser are you using?