开发者

jQuery - Unchecking checkboxes that act like radio buttons

I have the following jQuery code to make my checkboxes act like radio buttons, so that only 1 of the 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 checkboxes are layed out like the following:

<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 how i want it to work, not a problem, except once i click one of the 3, i cant unclick it so that none of th开发者_如何学Cem are checked, this is what i want to happen, so along with being only able to click one at a time, im able to uncheck them completely.

Any help would be grand :)


Only run the code that unchecks the others if this has been 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;
    }
});

EDIT: Here's a revision that prevents the newly checked box from being unchecked when you select the boxes with the same name. It uses not()(docs) to exclude the current checkbox.

Example: 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");
    }
});


Less Code! :-)

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

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


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

http://jsfiddle.net/yDPhv/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜