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 of empty string. The data-type of the returned value is still string. Is null a string value?
<input type="text" value="" id="mytext">
is the textbox whose value I am trying to fetch using var mytextvalue = document.getElementById("mytext").value;
This question is related to
javascript
string
dom
null
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" />
I think the textbox you are trying to access is not yet loaded onto the page at the time your javascript is being executed.
ie., For the Javascript to be able to read the textbox from the DOM of the page, the textbox must be available as an element. If the javascript is getting called before the textbox is written onto the page, the textbox will not be visible and so NULL is returned.
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.
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?
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.
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.
Source: Stackoverflow.com