选中时jQuery复选框计数

时间:2014-07-15 16:19:13

标签: jquery

我有四个复选框。我需要检查是否至少选择了2个。他们不在任何DIV内。他们是独立的。只有在选择至少2个复选框时才会提交表格。

2 个答案:

答案 0 :(得分:0)

请尝试此代码。

<form id="submitForm" method="POST">

<input type="checkbox" name="checkboxname" id="checkboxname" value="check1"> check1
<input type="checkbox" name="checkboxname" id="checkboxname" value="check2"> check2
<input type="checkbox" name="checkboxname" id="checkboxname" value="check3"> check3
<input type="checkbox" name="checkboxname" id="checkboxname" value="check4"> check4

<input type="submit" name="proceed" value="proceed" id="proceed">
</form>

,jquery脚本是

$(document).ready(function(){
    $('#proceed').click(function(){
        alert('im triggered')
        alert($('#checkboxname:checked').length)
    });

});

试试吧。

答案 1 :(得分:0)

完整代码:

<!DOCTYPE>
<html>
<head>
    <meta charset="utf-8" />
    <title>jQuery Playground</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>

<body>
    <h1>Submit Form</h1>
    <p>Select two options below and submit form</p>
    <form action="action.php" method="post" id="myForm" enctype="application/x-www-form-urlencoded">
        <p>Select only 2 fruits you would like to have for dinner</p>
        <input type="checkbox" name="fruit" value="orange" class="fruit"> Oranges<br>
        <input type="checkbox" name="fruit" value="banana" class="fruit"> Bananas<br>
        <input type="checkbox" name="fruit" value="apple" class="fruit"> Apples<br>
        <input type="checkbox" name="fruit" value="grape" class="fruit"> Grape<br>
        <input id="go" type="submit" value="Go Button">
    </form>
    <script>
        jQuery( function( $ ){

            $("#myForm").on( "submit", function( e ){

                // check if 2 items have been checked                    
                if( $(".fruit:checked").length !== 2 ){
                    e.preventDefault();
                    return false;
                }
                // continue form submission if 2 items have been checked
            });
        });

    </script>
</body>