Skip to main content
Known Participant
August 18, 2009
Question

Required checkbox

  • August 18, 2009
  • 5 replies
  • 3078 views

I have a coldfusion form with <cfform> . I have 3 check boxes in the form that I need to make sure at least one of them has checked. How  can I do that.

I really appreciate if somebody can help me.

Thanks.

    This topic has been closed for replies.

    5 replies

    Inspiring
    August 20, 2009

    Provided that all three checkboxes have the same name, just use the built in cf validation ;

    <cfinput type="checkbox" name="cars" value="Honda" required="yes" message="Please check at least one car">Honda <br>

    <cfinput type="checkbox" name="cars" value="Ford"> Ford <br>

    <cfinput type="chekcbox" name="cars" value="Toyota">Toyota

    Inspiring
    August 19, 2009

    You can use JavaScript, server-side Cold Fusion code, or better yet, both. Remember, though, that JavaScript is only for user-friendly type of validation.In almost all cases, you really need to use server-side validation, because users can circumvent JavaScript. You can do the server-side validation in several ways, the code in the reply from gedecus will work well enough.

    August 19, 2009

    I googled 'javascript required checkbox' and found some good suggestions. Here's a simple one that looks good:

    <SCRIPT TYPE="text/javascript" LANGUAGE=JAVASCRIPT>

    function checkCheckBoxes() {
         if (document.frmTest.CHKBOX_1.checked == false &&
             document.frmTest.CHKBOX_2.checked == false &&
             document.frmTest.CHKBOX_3.checked == false)
              {
              alert ('You didn\'t choose any of the checkboxes!');
              return false;
              }
         else
              {
              return true;
              }
         }
    //-->
    </SCRIPT>



    <form onsubmit="return checkCheckBoxes();" action="">
    <input type="checkbox" name="CHKBOX_1" value="1">1</p>
    <input type="checkbox" name="CHKBOX_2" value="2">2</p>
    <input type="checkbox" name="CHKBOX_3" value="3">3</p>
    <input type="submit" value="Submit!" />
    </form>
    Inspiring
    August 19, 2009

    That only works when each checkbox has a different name.  It's often the case that they all have the same name.  In this case, the ever popular GetElementById comes into play.

    August 19, 2009

    There are many ways to do it. But it all really depends on what form validation you're using now.

    You could do something like:

    <cfif IsDefined("form.submit")>

         <cfif NOT IsDefined("form.checkbox1") AND NOT IsDefined("form.checkbox2") AND NOT IsDefined("form.checkbox3")>

              code to process form as error

         </cfif>

    </cfif>

    Prasanth_Kumar_S
    Inspiring
    August 18, 2009

    may be JavaScript is the answer.