Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

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;

like image 484
Guruprasad Avatar asked Jun 27 '11 10:06

Guruprasad


4 Answers

Posting your HTML might help a bit. Instead, you can get the element first and then check if it is null or not and then ask for its value rather than just asking for the value directly without knowing if the element is visible on the HTML or not.

element1 = document.getElementById(id);

if(element1 != null)
{
    //code to set the value variable.
}
like image 184
ilight Avatar answered Sep 17 '22 11:09

ilight


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.

like image 24
Ivan Town Avatar answered Sep 20 '22 11:09

Ivan Town


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.

like image 37
user4989959 Avatar answered Sep 20 '22 11:09

user4989959


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?

like image 27
Aziz Shaikh Avatar answered Sep 18 '22 11:09

Aziz Shaikh