views:

35

answers:

2

Hi, 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].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(); 
    }    
}
+1  A: 
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.

Sparafusile
+1  A: 

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;
casablanca
You have an "off by one" error in your loop. Can you guarantee that "c[i].type" will be lowercase?
Sparafusile
:) I overlooked the indexing error when I copy-pasted the OP's code. And yes, I'm quite sure the type is lowercase in most browsers.
casablanca