简体   繁体   中英

Auto disable other checkboxes using html.checkboxfor once one is selected

I am trying to disable other checkboxes on selection of one checkbox and enable again if this has again been de-selected.
Below is a snippet of code I found that worked during an example fiddle for a standard checkbox but I have not been able to replicate this for a checkboxfor, can someone please recommend the changes I need to make in order for this to work in a checkboxfor?

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

And below is my checkboxfor where I am calling this

@Html.CheckBoxFor(modelItem => item.IsDisplayImage, new { id = "chkItems" })

You can use this code if want to persist using checkboxes otherwise its better to use radio button instead

HTML

<label class="checkbox-inline check">
      <input type="checkbox" name="skills" id="radio" value="1"> 1
</label>
<label class="checkbox-inline check">
      <input type="checkbox" name="skills" value="2"> 2
</label>
<label class="checkbox-inline check">
      <input type="checkbox" name="skills" value="3"> 3
</label>

JS:

$('.check input:checkbox').click(function() {
    $('.check input:checkbox').not(this).prop('checked', false);
});  

Check this jsfiddle for the demo

You can use radio buttons as :

<form>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other  
</form> 

Okey. For example you have model ForRadioButtonsModel like

public class ForRadioButtonsModel
    {
        public int Id { get; set; }
        public bool IsDisplayImage { get; set; }
    }

On View You pass Collection of this models or model that contains this collection

return View((List<ForRadioButtonsModel>) collection);

Than In view you can do next to create RadioGroup

@foreach (var item in Model) <-- Model is of type List<ForRadioButtonsModel>
{
     @Html.RadioButtonFor(m => item.IsDisplayImage, item.IsDisplayImage) 
}

This will render next HTML

<input checked="checked" id="item_IsDisplayImage" name="item.IsDisplayImage" type="radio" value="True">
<input checked="checked" id="item_IsDisplayImage" name="item.IsDisplayImage" type="radio" value="False">

So You will have radioButtons with same name, but with different values

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