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

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

本文关键字:is null getElementById TypeError document Javascript      更新时间:2023-09-26

这是我html代码:

<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>

在标题中,我包含我的JavaScript文件和以下特定代码:

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;
  }
}

我尝试使用 console.log(getValues("searchForm") ); 访问该功能,但在Firefox控制台中,我收到以下错误:TypeError: form is null .

谁能建议为什么这不起作用?

您使用的是name属性的值,而不是id。因此,您需要将name更改为id或使用

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

另请注意,如果您使用上面的代码,它将返回 NodeList因此您需要使用 index 来获取所需的元素。

获取表单的所有值:

"use strict";
var findValuesIn = function(form) {
  
  var fields = form.querySelectorAll('input,textarea,select'),
      values = {},
      i;
  
  for (i in fields) {
    values[ fields[i].name ] = fields[i].value; 
  }
  
  return values;
  
}
document.getElementById('obtainValues').addEventListener('click',function(){
  var ourForm = document.getElementById('f');
  
  var vals = findValuesIn(ourForm);
  
  // debug
  document.getElementById('debug').innerHTML = JSON.stringify(vals);
  
});
input, select, textarea {
  float: left;
}
button {
  float: left;
  clear: both;
  margin: 1em;
}
label {
  float: left;
  clear: left;
  width: 10em;
}
output {
  display: block;
  clear: both;
  margin: 1em;
  padding: .5em;
  border: 1px solid gray;
  background-color: #eee;
}
<form name="f" id="f">
  <label for="name">Name</label>
  <input type="text" name="name" />
  
  <label for="search">Search</label>
  <input type="search" name="search" />
  
  <label for="favouriteColour">Favourite Colour</label>
  <select name="favouriteColour">
    <option>red</option>
    <option>blue</option>
    <option>yellow</option>
  </select>
  
  <button id="obtainValues">obtain values</button>
  
</form>
<output id="debug" form="f"></output>