简体   繁体   中英

How do I disable a checkbox when another checkbox is ticked & re-enable when unticked?

I am currently using Javascript to try attempt this, could it be the way I am linking the checkbox to the script? If so any advice would be helpful. Edit- The checkboxes are within a foreach loop and radio boxes will not work as this is not the exact situation I am using this in.

Checkboxes

@Html.CheckBoxFor(modelItem => item.ambassador, htmlAttributes: new { @class = "checkbox", type = "checkbox" })

@Html.CheckBoxFor(modelItem => item.groupSelection, htmlAttributes: new { @class = "checkbox", type = "checkbox" })

Javascript

<script>
    $('.checkbox').change(function () {
        $(this).siblings('.checkbox').prop('disabled', this.checked);
    });
</script>

The Javascript code is from this question: Disable Checkbox on selecting another checkbox in mvc4

HTML already has a built-in for this, they're called radio buttons :

 <form> <input type="radio" name="option" value="first"> <label for="first">first</label> <input type="radio" name="option" value="second"> <label for="second">second</label> </form> 

From EchoEcho :

Radio buttons are used when you want to let the visitor select one - and just one - option from a set of alternatives. If more options are to be allowed at the same time you should use check boxes instead.

Because you only want the user to be able to select one of the two options at a time, you should use radio buttons.

See also this ux.SE post on the subject.

maybe your checkboxes are being loaded after the script is loaded.. ajax? partial? try adding the listener to your body or a parent element

 $(function(){ $('body').on('click', '.checkbox', function () { $(this).siblings('.checkbox').prop('disabled', this.checked); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="checkbox" type="checkbox"></input> check 1<br> <input class="checkbox" type="checkbox"></input> check 2<br> <input class="checkbox" type="checkbox"></input> check 3<br> <input class="checkbox" type="checkbox"></input> check 4<br> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM