SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot Rio's Avatar
    Join Date
    Nov 2001
    Location
    United Kingdom
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Limit the number of checkboxes checked

    Hi,

    I'm making an online form-to-mail form (using mail() function in PHP) with 10 checkboxes. There's nothing complicated about this page, but the viewers shoule only choose 3 checkboxes.

    Is there any way to limit the number of boxes checked? It would be even better if it returns the error message when a viewer selects more than 3 boxes.

    Somebady told me that the javascript is the answer

  2. #2
    ********* obeah makeda's Avatar
    Join Date
    Jun 2001
    Location
    rollin' on dubs
    Posts
    492
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, start out by setting a global variable equal to 0:

    Then set a function to fire each time someone clicks on a checkbox. If the checkbox is checked, increment the counter, if the checkbox is unchecked, decrement the counter. If someone checks a checkbox and your counter is equal to three, uncheck the checkbox and throw an error


    <script type="text/javascript">
    var iCounter = 0;


    function checkCounter(refChkBox) {

    //if they checked the checkbox do this
    if(refChkBox.checked) {

    //3 checkboxes have been checked
    if(iCounter >= 3) {
    refChkBox.checked = false;
    alert("You can only select 3 checkboxes.");
    }
    else {
    iCounter++;
    }

    //if they unchecked the checkbox, do this
    else {
    iCounter--;
    }

    }

    </script>

    <input type="checkbox" id="chkOne" value="" onClick="checkCounter(this)" />


    I haven't tested this, but it should work.

  3. #3
    SitePoint Zealot Rio's Avatar
    Join Date
    Nov 2001
    Location
    United Kingdom
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks makeda. Guys in PHP forum helped me to do the job in php this time around. But I will try your script on non-php sites.

    Chrees!

  4. #4
    ********* obeah makeda's Avatar
    Join Date
    Jun 2001
    Location
    rollin' on dubs
    Posts
    492
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    what??!! server side INSTEAD of client-side??!!

    only kidding

    good luck.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •