要检查必填字段和警告用户缺少必填字段的自定义方法,我正在尝试获取表单中的元素数组,并且一直在寻找但没有找到好的方法.
是否有一些变化
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); } }
Hatchet.. 9
尝试querySelectorAll
使用属性选择器:
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") + "
";
}
o.innerHTML = s;
});
[required] {
outline: 1px solid red;
}
Required inputs
尝试querySelectorAll
使用属性选择器:
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") + "
";
}
o.innerHTML = s;
});
[required] {
outline: 1px solid red;
}
Required inputs