Jump to content

Checking to see if at least one checkbox is checked?


galvin

Recommended Posts

I have a form with several checkbox inputs that submits to a PHP page via Post and the selected checkboxes are posted to an array (each input has a name of "checkedboxes[]" so that an array is created in $_POST['checkedboxes']);

 

However, before it submits, I want to use javascript to make sure the user checked at least one checked. I know how to check it using PHP, but again, I want to do it without leaving the page, so I want to use javascript.

 

Can anyone help?    I've googled and it seems I will have to use something like onclick='return validate();' or maybe onsubmit='return validate();' but I am having trouble obviously, figuring out how to actually check in the validate function (if that is in fact the right way to do it).

 

Here's the example code.  Again, just want to make sure the user checks at least ONE of those 4 boxes...

 

<form id="form" method="post" action="nextstep.php">
<input type="checkbox" name="checkedboxes[]" value="1">
<input type="checkbox" name="checkedboxes[]" value="2">
<input type="checkbox" name="checkedboxes[]" value="3">
<input type="checkbox" name="checkedboxes[]" value="4">
<input type='submit' name='submit' value='Submit' />
</form>

Link to comment
Share on other sites

Follow up...  Using my same example, is there a way using JQuery to trigger an event when any one of my checkboxes is checked? 

 

I found this code below online, but this is checking one specific checkbox.  I might have  A LOT of checkboxes, so I'd rather not have to have a click function for every one of my individual checkboxes,  looking to see if one is checked...

 

$('#myCheckBox').click (function ()
{
var thisCheck = $(this);
if (thischeck.is (':checked'))
{
// Do stuff
}
});

 

I feel like I should be able to use a similar version of .josh's reply earlier, i.e something like....

 

  if ($(this).find('input[name="checkedboxes[]"]:checked').length == 1) {
      alert('someone checked a box!');
     }

 

But I can't figure out how I would run that code WHEN someone checks any one of my potentially many checkboxes.  Any ideas?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.