black_belt
black_belt

Reputation: 6799

Jquery Checkbox Input Validation

I have the following checkbox

<input type="checkbox" name="compare[]" value="<?php echo $product_id  ?>" />

Now, I want to let my users select minimum three and maximum three options from the above check box. Breaking of any of the rules would give a message.

Would you please kindly help me how to do that with Jquery?

Thanks in Advance

Upvotes: 0

Views: 480

Answers (3)

Midio
Midio

Reputation: 36

You can loop over your checkbox's using jQuery.each(), checking for checked items and adding checks to a count. Then if the count is not equal to 3 you can output the validation error message.

$(function(){
$("#frm").submit(function(){
    var checkCount = 0;
    var min = 3;
    var max = 3;

    // iterate over checkbox's using jquery each()
    // use jquery's attribute contains selector ( http://api.jquery.com/attribute-contains-selector/ )
    // to grab the compare portion of the checkbox field name
    $("input[name*='compare']").each(function(k, v) {

    // increment check count when a checked checkbox is found
    if($(this).is(":checked"))
        checkCount++;
    });

    //validate checkbox count against predefined range
    if(checkCount < min || checkCount > max)
    {
        console.log("Checkbox Validation Failed");
        return false;
    }
    else
        console.log("Checkbox Validation Passed");

});
});

Upvotes: 0

uadnal
uadnal

Reputation: 11445

Here is a 1 solution

var $chkbox = $('input[name=compare]');
$chkbox.click(function (e) {
    if ($chkbox.filter(':checked').length > 3) {
        e.target.checked = false;
    }
});

http://jsfiddle.net/H96nz/

var $chkbox = $('input[type="checkbox"]');

$chkbox.click(function (e) {
    if ($chkbox.filter(':checked').length > 3) {
        e.target.checked = false;
    }
});

Upvotes: 2

Related Questions