简体   繁体   中英

need to select atleast one checkbox using javascript

I am using this javascript code. and on button click I want that atleast one checkbox selection is required. do anyone have idea what I am doing wrong. I don't want to use jquery.

function check()
{
var flag = false;
for(var i=1;i<=4;i++)
{
  var checkb = document.getElementById("check"+i);

  if(checkb.checked)
  {
    flag = true;
    break;
  }
}
if(!flag)
alert("What is your interest \n(select at least one option)");
return flag;
}
</script>

Button Click Code is

<input type="submit" name="submit" value="Submit" onclick="return check();">

The code works fine. Do hou have id="check1" set on your checkbox tags?

Yes, your code works fine as noted by the comments above. However, you could do your check for...checks a little more cleanly - you're expecting "check0" - "check4" for the IDs. You could just grab them all and not worry about a set limit (odds are your code isn't working because at least one of the IDs you're using doesn't exist).

<input type="checkbox" id="check0" />
<input type="checkbox" id="check1" />
<input type="checkbox" id="check2" />
<input type="checkbox" id="check3" />
<hr/>
<input type="button" onclick="checkIt();" value="Check the Checks">

And some JS:

checkIt = function()
{
    var checks = document.getElementsByTagName('input');
    var hasCheck = false;  
    for(i in checks)
    {
        // Could also check for a classname here to narrow 
        // your result set.
        if(checks[i].type == 'checkbox')
            hasCheck |= checks[i].checked;
    }

    if(!hasCheck)
        alert('You should check one!');

    return hasCheck;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM