4

I have the following piece of html code for form checkboxes

<div class="drinking col-xs-12">
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="allwines" id="allwines" value="0" class="require-one col-xs-1 styled myClassA"  value="0" data-label="All Wines" />
    <input id='allwinesHidden'  type='hidden' value='0' name='allwines'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="beer" id="beer" value="0" class="require-one col-xs-1 styled myClassB"  value="0"  data-label="Beer" />
    <input id='beerHidden'  type='hidden' value='0' name='beer'>
  </div>
  <div class="clearix"></div>
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="redwines" id="redwines" value="0" class="require-one col-xs-1 styled myClassC"  value="0" data-label="Red Wines" />
    <input id='redwinesHidden'  type='hidden' value='0' name='redwines'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="cider" id="cider" value="0" class="require-one col-xs-1 styled myClassD"  value="0" data-label="Cider" />
    <input id='ciderHidden'  type='hidden' value='0' name='cider'>
  </div>
  <div class="clearix"></div>
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="whitewines" id="whitewines" value="0" class="require-one col-xs-1 styled myClassE"  value="0" data-label="White Wines" />
    <input id='whitewinesHidden'  type='hidden' value='0' name='whitewines'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="spirits" id="spirits" value="0" class="require-one col-xs-1 styled myClassF"  value="0" data-label="Spirits" />
    <input id='spiritsHidden'  type='hidden' value='0' name='spirits'>
  </div>
  <div class="clearix"></div>
  <div class="col-xs-7 drinkingLeft">
    <input type="checkbox" name="sparkling" id="sparkling" value="0" class="require-one col-xs-1 styled myClassG"  value="0" data-label="Sparkling/Champagne" />
    <input id='sparklingHidden'  type='hidden' value='0' name='sparkling'>
  </div>
  <div class="col-xs-5 drinkingLeft">
    <input type="checkbox" name="fortified" id="fortified" value="0" class="require-one col-xs-1 styled myClassH"  value="0" data-label="Fortified" />
    <input id='fortifiedHidden'  type='hidden' value='0' name='fortified'>
  </div>
  <div id="error_msg3"></div>
  <div class="clearix"></div>
</div>
</div>

I want to make sure that at least one of the check boxes is selected.

I want that NOT as an alert box ; however the message need to show up in the div error-msg3.

Please note that all the inputs have different class names and ids. A staging link is at

https://bitly.com/1i3f1MY

I am using jQuery validation to validate rest of the form. Will be nice to get solution through jquery validation.

Thanks in advance

3
  • I added the code in a jsfiddle. jsfiddle.net/dHrvT/15 Nov 28, 2013 at 10:39
  • Updated jsfiddle jsfiddle.net/dHrvT/17 Nov 28, 2013 at 11:39
  • Just reiterating again : * the names/ids of each of the checkboxes are different * When user clicks the submit button I need the following: * If no checkbox is clicked, then the error message to show up just like the other error message * when one of the checkbox is checked, the error message needs to be hidden again* and if user unclicks all error message again, the error message needs to be shown again. ANd no, I can not have the names all the same. It is using custom checkbox (pretty checkbox). Nov 28, 2013 at 11:44

5 Answers 5

7
+50

You will have to change the name attributes of the checkboxes, and add a rule for it with the minlength set to 1.

You can after show the custom message and append it to #error_msg3 with :

if(element.attr("name") == "check") error.appendTo("#error_msg3")

EDIT

$("input[type='checkbox'][name='check']").change(function() {
    if ($("input[type='checkbox'][name='check']:checked").length){
        $(this).valid()
    }
})

EDIT 2

I've updated the Fiddle, now the message toggles correctly when you have at least one checkbox checked or not.

$("input[type='checkbox'][name='check']").change(function() {
    $('#submitDetails').valid();
});


Fiddle here

6
  • I tried your jsfiddle. When I click on the submit button and no checkbox is checked, I do get the error message. However, when the checkbox is checked now, the error message does not disapear.. also it should toggle on and off with checkbox being checked and not checked.. That is, when there is nothing checked it should have the error message.. and when checked the error message disseapers just like other error fields Nov 29, 2013 at 4:15
  • To remove error message when a checkbox is checked, I've updated the Fiddle, see edit.
    – Preview
    Nov 29, 2013 at 10:29
  • Thanks. HOwever, it does not come back up again if user unclicks it. So let us say that user clicks submit button he gets the error message. When user choses one of the checkbox, error message disappears. (Fine till now). however, if user now decide to unclick checkbox, error message should reappear right. It should toggle with on change right Nov 30, 2013 at 5:03
  • Thanks. But I noticed something when I tried to implement it. You changed the name property of each of the concerned elements so that they all have the same names. To start with the idea was that they will have different names :). So basically your solution did not help me at the end. But thanks for trying and cheers Dec 2, 2013 at 23:39
  • Checkboxes should have the same name, if you want to target a particular one, you need to take the id.
    – Preview
    Dec 2, 2013 at 23:45
7

This is very simple......

function validate_form()
{
valid = true;

if($('input[type=checkbox]:checked').length == 0)
{
    alert ( "ERROR! Please select at least one checkbox" );
    valid = false;
}

return valid;
}

HTML

<form name="myform" method="post" action="#" onsubmit="return validate_form();">
<input type="checkbox" name="box1"  value="box1">Box1
<input type="checkbox" name="box2"  value="box2">Box2
<input name="submit" type="submit" value="Submit"/>
</form>
3

Quote OP:

"I want to make sure that at least one of the check boxes is selected."

If you want to use the jQuery Validate plugin, and all checkboxes have a different name, simply use the require_from_group method that's part of the additional-methods.js file.

Since you already have a common class on these checkboxes called require-one, it's even easier.

$('#form').validate({
    rules: {
        fieldname: {
            require_from_group: [1, '.require-one']
        },
        // declare same rule on all eight checkboxes
        ....
        ....
    }
});

However, rather than declare all eight of these within .validate(), you can use the .rules('add') method inside of a jQuery .each() to declare them all at once.

$('.require-one').each(function () {
    $(this).rules('add', {
        require_from_group: [1, this],
        messages: {
            require_from_group: "please check one"
        }
    });
});

Then to combine all eight messages into one, use the groups option...

$('#form').validate({
    groups: {  // combine these error messages into one
        checkboxes: 'allwines beer redwines cider whitewines spirits sparkling fortified'
    }
});

Working DEMO: http://jsfiddle.net/JVWu2/1/

Placing your error message into the #error_msg3 error box is no different than placing any of your other jQuery Validate messages.

3
  • Hi @Sparky , I have added my codes inside a jsfiddle jsfiddle.net/dHrvT/15 . However, is it ok for you to add your solution and let me know if it works. I tried in real staging links and was unable. I do believe your solution works.. I just can't seem to integrate one with the other Nov 28, 2013 at 10:40
  • @Himu, I fully answered your question as you originally posted it. There was nothing mentioned in your OP about integrating this with prettyCheckable. IMO, this is a whole different issue. The jQuery Validate plugin is only looking at your real checkbox elements and until you can figure out how to toggle those, this is never going to work.
    – Sparky
    Nov 28, 2013 at 16:56
  • @Himu, I also notice that your jQuery code is unnecessarily repetitive. Nearly all of your .on('change') handlers could be combined into one and you should only need to call .prettyCheckable() one time. It's just a matter of using the proper jQuery selectors to select all target elements at once.
    – Sparky
    Nov 28, 2013 at 17:03
2

Try with this

$("#YourbuttonId").click(function(){
    if($('input[type=checkbox]:checked').length == 0)
    {
        alert('Please select atleast one checkbox');
    }
});

By Plugin

HTML

<label class="checkbox inline">
<input type="checkbox" id="typecb1" name="spamm[]" value="Loading Point"> Loading Point
</label>
<label class="checkbox inline">
<input type="checkbox" id="typecb2" name="spamm[]" value="Unloading Point"> Unloading Point
</label>
<label class="checkbox">
<input type="checkbox" id="typecb3" name="spamm[]" value="Retailer Unloading"> Retailer Unloading
</label>

Script

rules:{
     "spamm[]": { 
      required: true, 
      minlength: 1 
      }
   }
1
  • 1
    Please no alert box. As I said no alert box. If possible as a solution integrated with jQuery validation plugin as said Nov 23, 2013 at 7:40
2

Try

adding this code will do

var chck = $('input[type=checkbox]');
chck.addClass('check-one');
$.validator.addMethod('check-one', function (value) {
    return (chck.filter(':checked').length > 0);
}, 'Check at least one checkbox');


fiddle Demo

Group will show error in front first check-box only

var chck = $('input[type=checkbox]');
chck.addClass('check-one');
$.validator.addMethod('check-one', function (value) {
    return (chck.filter(':checked').length > 0);
}, 'Check at least one checkbox');
var chk_names = $.map(chck, function (el, i) {
    return $(el).prop("name");
}).join(" ");
$("#submitDetails").validate({
    groups: {
        checks: chk_names
    },
    submitHandler: function (form) {
        alert('Form Submited');
        return false;
    }
});


Remove group if you want error to show in front of all check-boxes

fiddle Demo

$("#submitDetails").validate({
    submitHandler: function (form) {
        alert('Form Submited');
        return false;
    }
});
4
  • Thanks Tushar. Your answer is so close. You can see it here bitly.com/1i3f1MY It works in the jsfillde. What am I doing wrong? Here is the js file I am using bit.ly/1aNWWMl You can see the code I added. When clicked on the submit button, it shows up after all the labels... not like the way in jsFiddle. It needs to be kinda like the jsFiddle... When submit button clicked, it should show up inside <div id="error_msg3"></div> and when any checkbox is clicked, the error message should disappear. Nov 23, 2013 at 8:14
  • Hi there. Tried to fix it. Couldnt. Let me know if you can help me solve this. Thanks Nov 23, 2013 at 8:28
  • @Himu See this Demo with your full form code. Nov 23, 2013 at 9:17
  • Please see the jsfiddle. I have added my code there Couldn't get it working with your code per say...So can you give it a try...please Nov 28, 2013 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.