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

前端 未结 8 1743
清酒与你
清酒与你 2021-01-17 17:09

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

相关标签:
8条回答
  • 2021-01-17 17:42

    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.

    0 讨论(0)
  • 2021-01-17 17:43

    It seems that you've omitted the value attribute in HTML markup.

    Add it there as <input value="" ... >.

    0 讨论(0)
  • 2021-01-17 17:46

    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.

    0 讨论(0)
  • 2021-01-17 17:48
    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" />
    
    0 讨论(0)
  • 2021-01-17 17:50

    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.

    0 讨论(0)
  • 2021-01-17 17:58

    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?

    0 讨论(0)
提交回复
热议问题