1. 程式人生 > >關於最多隻能選擇兩個多選框的jQuery功能實現

關於最多隻能選擇兩個多選框的jQuery功能實現

<body>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function()
            {
                $(':checkbox').each(function()
                {
                    $(this).click(function()
                    {
                        limit_select_two_options(this);
                    });
                });
            }
        );
            function limit_select_two_options(obj)
            {
                var count=0;
                var arr=[];
                $(':checkbox').each(function()
                {
                    if($(this).attr('checked')==true)
                    {
                        arr.push($(this));
                        count++;
                    }
                });

                if(count>2)
                {
                    if($(obj).attr('value')==arr[0].attr('value'))
                    {
                        arr[arr.length-1].attr('checked',false);
                    }
                    else
                    {
                        arr[0].attr('checked',false);
                    }
                }
                return true;
            }

        </script>

        <input type="checkbox" value="1"  /><br/>
        <input type="checkbox" value="2"  /><br/>
        <input type="checkbox" value="3"  /><br/>
        <input type="checkbox" value="4"  /><br/>
        <input type="checkbox" value="5"  /><br/>
        <input type="checkbox" value="6"  /><br/>
        <input type="checkbox" value="7"  /><br/>
        <input type="checkbox" value="8"  /><br/>
        <input type="checkbox" value="9"  /><br/>
        <input type="checkbox" value="10"  /><br/>
    </body>