Search code examples
javascripthtmlformstypeerrorgetelementbyid

Javascript TypeError: document.getElementById(...) is null


Here is my html code:

<form name="searchForm" action="javascript:;" method="post" />
  <p>
   <label for="search">Search the site:</label>
   <input type="text" id="search" name="search" value="xhr" />
   <input type="submit" value="Search" />
 </p>
</form>

In the header, I included my JavaScript file with the following specific code:

window.onload = function () {
    getValues = function (id) {
    var i, values = [], form = document.getElementById(id);
    for (i = 0; i < form.length ;i++) {
        values.push( form.elements[i].value );
    }
    return values;
  }
}

I've tried to access the function with console.log(getValues("searchForm") ); but instead in my Firefox console, I received the following error: TypeError: form is null.

Can anyone suggest why this doesn't work?


Solution

  • You're using name attribute's value, not id. So either you need to change name to id or use

    form = document.getElementsByName(id)[0];
    

    Also note that if you use the above code, it will return NodeList so you need to use index to get the desired element.