Home > front end >  razor, jquery: when checkbox is checked uncheck some other checkboxes, but it unchecks ALL checkboxe
razor, jquery: when checkbox is checked uncheck some other checkboxes, but it unchecks ALL checkboxe

Time:09-20

I have a few checkboxes on my page. One is rendered statically, while the others are rendered from the model:

 <table>
     <tr>
         <td>
             @Html.CheckBoxFor(m => m.AllLangsChecked, new { onchange = "checkedChanged" })
             <script>
                 $('input:checkbox').change(function () {
                     $('input:checkbox').not(this).prop('checked', false);
                 })
             </script>
             <label>Alle Sprachen</label>
         </td>
     </tr>
     @for (int i = 0; i < Model.checkLangs.Count; i  )
     {
         <tr>
             <td>
                 @Html.HiddenFor(m => m.checkLangs[i].Name)
                 @Html.HiddenFor(m => m.checkLangs[i].LanguageId)
                 @Html.CheckBoxFor(m => m.checkLangs[i].isChecked)
                 <label>@Model.checkLangs[i].Name</label>
             </td>
         </tr>
     }
 </table>

Now you can see my tag. Its job is basically to uncheck all of the dynamic checkboxes when the top one is checked.

This does work fine. However, the script also unchecks litereally ALL checkboxes on that page. (there are a few more).

But I only want those from the loop to be disabled.

How would you go on about this?

Thank you!

CodePudding user response:

I am not good about that razor syntax I guess
But I have some thoughts about jquery problem
You jquery selector works for all input:checkbox on the page
So you should add some more selectors for checkboxes that you need
Try to add class to your table tag
and add that class to your jquery checkbox selector query
something like that

<table >
     <tr>
         <td>
             @Html.CheckBoxFor(m => m.AllLangsChecked, new { onchange = "checkedChanged" })
             <script>
                 $('.some-class input:checkbox').change(function () {
                     $('.some-class input:checkbox').not(this).prop('checked', false);
                 })
             </script>
             <label>Alle Sprachen</label>
         </td>
     </tr>
     @for (int i = 0; i < Model.checkLangs.Count; i  )
     {
         <tr>
             <td>
                 @Html.HiddenFor(m => m.checkLangs[i].Name)
                 @Html.HiddenFor(m => m.checkLangs[i].LanguageId)
                 @Html.CheckBoxFor(m => m.checkLangs[i].isChecked)
                 <label>@Model.checkLangs[i].Name</label>
             </td>
         </tr>
     }
 </table>

this jquery selector works only for checkbox inside the table

  • Related