我有多个复选框。单击“提交”按钮时,我想检查是否至少选中了一个复选框。它无法正常工作
function doSubmit(){
function check_checkboxes()
{
checked=false;
var c = document.getElementsByTagName('input');
for (var i = 1; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {
return true}
else {alert("Please identify what warehouses comply:"); }
}
}
document.holiDay.command.value= 'addingApp'; //My struts Action to perform if selected
document.holiDay.submit();
}
}
答案 0 :(得分:1)
function doSubmit()
{
var c = document.getElementsByTagName('input');
for( var i = 0; i < c.length; i++ )
{
if( c[i].type.toLowerCase() == 'checkbox' && c[i].checked )
{
// A checkbox was checked, good user
return( true );
}
}
// No checkbox checks, bad user
return( false );
}
我建议您阅读一本关于JavaScript的书,因为您似乎刚刚开始。一本关于编码风格和一致性的书也不会受到影响。
答案 1 :(得分:1)
您的alert
应该在for循环之外,否则您将为每个未选中的复选框弹出一条消息,即使实际检查了其中一个。这样的事情应该有效:
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox' && c[i].checked == true) {
// At least one checkbox IS checked
document.holiDay.command.value= 'addingApp'; //My struts Action to perform if selected
document.holiDay.submit();
return true;
}
}
// Nothing has been checked
alert("Please identify what warehouses comply:");
return false;