Jump to content

Limit selection of check box


EHTISHAM

Recommended Posts

Limit selection of check box

 

My code looks like...

foreach($res as $res)
    echo '<div class="ediv"><input type="checkbox" class="echeck" name="pr[]" value="'.trim($res['product']).'"/>'.trim($res['product']).'</div>';

How to set limit of selection of dynamically created checkboxes...??

Link to comment
Share on other sites

I have to wonder if

foreach ($res as $res)

 

will work.  You are supplanting the $res variable with a new value so you lose the rest of the array!

 

Try

foreach ($res as $item)

instead and then manipulate $item

it works.. thanks for sharing knowledge..  i'll change $res to $item..

 

How to set limit of selection of dynamically created checkboxes...??

Link to comment
Share on other sites

If you want to do it before the user submits the form, use JavaScript. When a select box is checked, increment a variable. When the user tries to select the fifth checkbox, pop up an alert box and uncheck the last selection. Of course, you'll have to decrement the variable when a select box is deselected.

Link to comment
Share on other sites

 

Unchecked boxes aren't submitted at all, so you just have to count the elements of $_POST['pr'] (if you're using the POST method):

if (isset($_POST['pr']) && count($_POST['pr']) > 4)
{
    echo 'You can select at most 4 options.';
}

I have to do it before submit the form.. any idea?

Link to comment
Share on other sites

If you want to do it before the user submits the form, use JavaScript. When a select box is checked, increment a variable. When the user tries to select the fifth checkbox, pop up an alert box and uncheck the last selection. Of course, you'll have to decrement the variable when a select box is deselected.

Will you please share the code of java script function to do this..

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.