开发者

How can I prevent a user from selecting multiple checkboxes in HTML?

How can I prevent a use开发者_StackOverflow社区r from selecting multiple checkboxes in HTML?


you should change it to radio button instead of check box!

<input type="radio" name="group1" id="item1" value="Milk">
<label for="item1">Milk</label>
<br/>
<input type="radio" name="group1" id="item2" value="Butter" checked>
<label for="item2">Butter</label>
<br/>
<input type="radio" name="group1" id="item3" value="Cheese">
<label for="item13">Cheese</label>


I had a use case where I needed use checkboxes--which, unlike radio buttons, allows a user to UNcheck... Here's an example of something I pieced together from another stackoverflow user:

<head>
    <meta charset=utf-8 />
    <title>and-or checkboxes</title>
    <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>

<body>

    <label for="checkbox1"><input type="checkbox" id="checkbox1" name="checkbox1" value="and" </label><span id="span_and">checkbox1</span><br>

    <label for="checkbox2"> <input type="checkbox" id="checkbox2"  name="checkbox2"  value="or" </label><span id="span_or">checkbox2</span>

    <script>

        $(document).ready(function(){
            $('#checkbox1').click(function() {
            var checkedBox = $(this).attr("checked");
                if (checkedBox === true) {
                    $("#checkbox2").attr('checked', false);
                } else {
                    $("#checkbox2").removeAttr('checked');                    
                }
            });
        });

        $(document).ready(function(){
            $('#checkbox2').click(function() {
            var checkedBox = $(this).attr("checked");
                if (checkedBox === true) {
                    $("#checkbox1").attr('checked', false);                     
                } else {
                    $("#checkbox1").removeAttr('checked');                       
                }
            });
        });

    </script>

</body>

With a little work, you can combine the either/or two scripts into a single script. You probably don't need this now but I wanted to post it because it was very useful to me.


If you want that only one checkbox get selected at a time then its better to use radiobutton instead.


If you mean that you don't want multiple checkboxes from a same "logical group" to be checked at one time, you should use radio buttons instead of checkboxes.

<form>
    <input type="radio" name="aGroup" value="choice1" /> Choice #1<br />
    <input type="radio" name="aGroup" value="choice2" /> Choice #2
</form>

By using this, only 1 option can be checked at one time


Use Radio, and they must have the same name="".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜