views:

149

answers:

2

Hi, I have number of checkboxes and another checkbox for "Select All"

I want to check if the user has selected at least one checkbox. Need modification in javascript

<script language="Javascript">

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:");  }
        } 
    } //if I place my struts action here..its not working?
}    
document.holiDay.command.value= 'addingApp'; //My Struts action if something checked. 
document.holiDay.submit(); 
}    
+1  A: 
var all=document.getElementById('holiDay');

In HTML IDs should be unique, so getElementById will only return 1 element. Perhaps you could try getElementsByTagName - http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx ?

Something like...

function check_checkboxes()
{
  var c = document.getElementsByTagName('input');
  for (var i = 0; i < c.length; i++)
  {
    if (c[i].type == 'checkbox')
    {
       if (c[i].checked) {return true}
    }
  }
  return false;
}

and change your Validate function to...

function Validate()
{
    if(!check_checkboxes())
    {
        alert("Please identify what warehouses comply:");  
        return false;
    }
    return true;
}
barrylloyd
Its not working. When I click the submit button, its not even going into the loop.[code]<script language="Javascript"> 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'; document.holiDay.submit(); }[/code]
oneofthelions
Ok, Ive added more to my original answer (see above)(Or see Jets answer - but I think this depends on Jquery?)
barrylloyd
A: 
 (function() {
  for(x in $ = document.getElementsByTagName("input"))
   with($[x])
    return (type == "checkbox" ? checked == true : 0)
 })
Jet
Please don't use `with`, or worse, suggest its use to others.
Matt Ball