开发者

On Submit - Check at least one checkbox

I have multiple check boxes. When the Submit button is clicked I want to check if at least one checkbox is selected. Its not working

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].che开发者_JS百科cked) {
        return true} 
        else {alert("Please identify what warehouses comply:");  }
            } 
        } 
        document.holiDay.command.value= 'addingApp'; //My struts Action to perform if selected
        document.holiDay.submit(); 
    }    
}


Your alert should be outside the for loop, otherwise you will be popping up a message for every checkbox that is not checked, even if one of them is actually checked. Something like this should work:

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;


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 );
}

I would suggest reading a book on JavaScript as it seems like you are just starting out. A book on coding style and consistency couldn't hurt either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜