要检查必填字段以及警告用户缺少必填字段的自定义方法,我正在尝试获取表单中的元素数组,并且一直在寻找但没有找到好的方法。
有一些变化吗?
document.getElementById(form).elements;
将返回数组中所有必需元素,或者测试是否需要给定元素的方法......类似于
var my_elements = document.getElementById(form).required_elements;
或
var my_elements = document.getElementById(form).elements;
for (var this_element in my_elements){
if (this_element.attributes["required"] == "false"){
my_elements.splice(this_element, 1);
}
}
答案 0 :(得分:8)
document.getElementById(form).querySelectorAll("[required]")
var requiredElements = document.getElementById("form").querySelectorAll("[required]"),
c = document.getElementById("check"),
o = document.getElementById("output");
c.addEventListener("click", function() {
var s = "";
for (var i = 0; i < requiredElements.length; i++) {
var e = requiredElements[i];
s += e.id + ": " + (e.value.length ? "Filled" : "Not Filled") + "<br>";
}
o.innerHTML = s;
});
&#13;
[required] {
outline: 1px solid red;
}
&#13;
<form id="form">
<input required type="text" id="text1" />
<input required type="text" id="text2" />
<input type="text" id="text3" />
<input type="text" id="text4" />
<input required type="text" id="text5" />
</form>
<br>
<button id="check">Check</button>
<br>
<div id="output">
Required inputs
</div>
&#13;