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

前端 未结 8 1761
清酒与你
清酒与你 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 18:01

    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.
    }
    
    0 讨论(0)
  • 2021-01-17 18:01

    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.

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