JQuery - unchecking boxes that act as radio buttons

I have the following jQuery code so that my checkboxes act like radio buttons so that only one of 3 can be checked at a time.

<script type="text/javascript" language="javascript">
$(document).ready(function() {
    $("#testing input:checkbox").change(function(){
        var checkname = $(this).attr("name");
        $("input:checkbox[name='" + checkname + "']").removeAttr("checked");
        this.checked = true;
    });
});
</script>

The flags are laid out as follows:

<input type="checkbox" id="testing" name="testing" value="B">
<input type="checkbox" id="testing" name="testing" value="I">
<input type="checkbox" id="testing" name="testing" value="A">

This works exactly the way I want it to work, and not a problem, except that once I click on one of the three, I cannot drop it so that none of them are checked, this is what I I want, only able to click one at a time, they managed to completely remove them.

Any help would be great :)

+5
source share
3 answers

Only execute code that cancels others if there thiswas one checked.

Example: http://jsfiddle.net/CX5Th/1/

$("#testing input:checkbox").change(function() {
    if( this.checked ) {
        var checkname = $(this).attr("name");
        $("input:checkbox[name='" + checkname + "']").removeAttr("checked");
        this.checked = true;
    }
});

: , . not() (docs), .

: http://jsfiddle.net/CX5Th/2/

$("#testing input:checkbox").change(function() {
    if (this.checked) {
        var checkname = $(this).attr("name");
        $("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
    }
});
+12

!: -)

var boxes = $("input:checkbox").click(function(){
    boxes.not(this).attr('checked', false);
});

http://jsfiddle.net/YqSXA/1/

+3
$("input:checkbox").click(function(){
    var ischecked = $(this).attr('checked');
    $('input:checkbox').attr('checked',false);
    $(this).attr('checked', ischecked);
});

http://jsfiddle.net/yDPhv/

0
source

All Articles