John
John

Reputation: 3945

how to select only one check box with JQuery

<div class="form-group">
@Html.CheckBoxFor(x => x.ClientAccountIsHospitality, new { @type = "checkbox" })
@Html.LabelFor(x => x.ClientAccountIsHospitality)
</div>
<div class="form-group">
@Html.CheckBoxFor(x => x.ClientAccountIsRetail, new { @type = "checkbox" })
@Html.LabelFor(x => x.ClientAccountIsRetail)
</div>

<script type="text/javascript" language="javascript">
         $(document).ready(function () {
            $("input[type='checkbox']").change(function () {
                $(this).closest(".checkboxContainer").find("input[type='checkbox']").not(this).prop("checked", false);
                $(this).prop("checked", true);
            });
        });
        </script>

I was hoping when a user selects a check box, the other check box will de-select, if it is selected. Problem with this code is user can select a check box but cant de-select it again. either by selecting another check box or trying to un select the selected box

NOTE I have used checkboxes through out my site and would like to stick to this. I do not want a radio button. thaks

Upvotes: 0

Views: 1407

Answers (1)

Aray Karjauv
Aray Karjauv

Reputation: 2945

$(':checkbox').click(function(e){
    if($(this).is(':checked')){
        $(':checked').prop('checked', false);
        $(this).prop('checked', true);

    }
    else{
        e.preventDefault();
    }
});

example

Upvotes: 3

Related Questions