我正在尝试编写一个javascript代码,该代码可以找到表单中的所有广播组,并检查以确保在每个组中单击一个。如果您知道表单和组名,这并不难。我想要做的是创建一些可以使用任何形式的'onsubmit'调用的代码。我希望保持代码的通用性,以便在不对每个表单进行自定义的情况下使用。
由于
答案 0 :(得分:1)
在提交处理程序期间,表单可通过this
关键字或event.currentTarget
属性获得。请注意,如果您使用内联事件处理程序,那么您可以将适当的变量传递给任何全局函数,例如: <form onsubmit="checkRadios(this);">
。然后,您可以遍历表单的elements
属性以查找单选按钮。
答案 1 :(得分:1)
演示:http://jsfiddle.net/rBaUM/16/
function onSubmitForSomeForm() {
var groups = {},
group;
[].forEach.call(this.elements, function (input) {
if (input.type === "radio" && input.name) {
groups[input.name] = groups[input.name] || [];
groups[input.name].push(input.checked);
}
});
for (group in groups) {
if (!groups[group].some(function (checked) {
return checked;
})) {
return false; //Some group was completely unchecked
};
}
return true;
}
console.log( "Both groups completely unchecked", onSubmitForSomeForm.call( document.myform ) );
document.myform.check_list2[0].checked = true;
console.log( "1st group completely unchecked", onSubmitForSomeForm.call( document.myform ) );
document.myform.check_list2[0].checked = false;
document.myform.check_list[0].checked = true;
console.log( "2nd group completely unchecked", onSubmitForSomeForm.call( document.myform ) );
document.myform.check_list2[0].checked = true;
console.log( "Both groups have checked checkbox", onSubmitForSomeForm.call( document.myform ) );
使用:
<form onsubmit="return onSubmitForSomeForm.call(this);"></form>
或者:
myform.onsubmit = onSubmitForSomeForm
或者:
myform.addEventListener( "submit", onSubmitForSomeForm, false );
答案 2 :(得分:0)
获取所有单选按钮并创建名称属性的数组。然后测试是否所有包含已检查的项目:
var radios = document.getElementsByTagName("input");
var names = {};
// Iterate over all inputs
for (var i=0; i<radios.length; i++) {
// Get the radio buttons
if (radios[i].type = "radio") {
// Add the name to an object
if (!names[radios[i].name]) {
names[radios[i].name] = false;
}
// Set the object property to true if this is checked
if (radios[i].checked) {
names[radios[i].name] = true;
}
}
}
// Now determine if any group is unchecked (still false)
for (var namegroup in names) {
if (!names[namegroup]) {
console.log(namegroup + " isn't checked");
}
}