Javascript TypeError: document.getElementById(...) is null
Javascript TypeError: document.getElementById(...) is null
这是我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>
相关文章:
- contentWindow.document.body is null
- document.getElementById(..) is null
- jquery TypeError: Response is null
- iframe contentDocument and contentWindow is null
- document.querySelector(...) is null error
- getElementById is null?
- Sbt 0.13 ScriptEngine is Null for getEngineByName(“JavaScrip
- AngularJS "localStorage.getItem" is null in $resou
- javascript canvas is null
- Sails.create even when item is null?
- Jquery ajax POST response is null
- Google App Engine: User is null
- Microsoft.XMLHTTP documentElement is NULL
- TypeError: this.element is null, Rails with Judge gem
- FileReader.readAsArrayBuffer return is null
- TypeError: jasmine.getEnv().currentSpec is null
- gapi.auth.authorize: TypeError: cv(...) is null
- Error document.getElementById is null
- Javascript TypeError: document.getElementById(...) is null
- JavaScript :TypeError: document.getElementById(...) is null