Home > front end >  Razor: Create Checkbox with Eventhandler
Razor: Create Checkbox with Eventhandler

Time:09-22

Usually, when I create checkboxes, I do it like this:

  @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>
                                                    }

I bind this to a model, and when the submit button is clicked, I react to the changes that have been made.

Now however, I want a checkbox that is not bound to any model but instead, if this is checked, it checks or unchecks ALL my other checkboxes.

My though is: add eventhandler -> alter model according to isChecked? -> do the rest via submit button.

But I couldnt find a tutorial on this. How would you go on about this?

Thank you!

CodePudding user response:

Try to use the following js:

<script>
        $('input:checkbox').change(function() {
            $('input:checkbox').not(this).prop('checked', false);
        })
</script>

result:

enter image description here

Update:

Try to add a class to the checkboxes:

@Html.CheckBoxFor(m => m.checkLangs[i].isChecked,,new{@})

And use the following js:

$('input.myClass:checkbox').change(function() {
            $('input.myClass:checkbox').not(this).prop('checked', false);
        })
  • Related