Add a client-side checkbox clicked handler to Razor view

13,195

Solution 1

how hide/show is a behavior I would use script, adding a class in checkbox:

@Html.CheckBoxFor(model => model.IsRecurring, new {@class "recurring"})


//event
$(".recurring input:checkbox").click(function () {
                   //hide/show
                });

Solution 2

You could try like this:

@Html.CheckBoxFor(model => model.IsRecurring, new {onchange = "checkedChanged"})

//JS
var checkedChanged = function () {
    alert("checkedChanged");
}
Share:
13,195
Maxim V. Pavlov
Author by

Maxim V. Pavlov

Part of the Universe and beyond.

Updated on June 09, 2022

Comments

  • Maxim V. Pavlov
    Maxim V. Pavlov almost 2 years

    The following markup generates an input of type checkbox with an id="IsRecurring" when a Razor view is sent to the browser.

    <div class="editor-label">
        @Html.LabelFor(model => model.IsRecurring)
    </div>
    
    <div class="editor-field">
        @{
            @Html.EditorFor(model => model.IsRecurring)
        }
    </div>
    

    I need to show/hide other markup block, based on the checked state of the checkbox.

    Which is the most MVC3 way to do it?

    My plan is to go with adding the following script above the div:

    <script type="text/javascript">
        $("#IsRecurring").click(function () {
            do show hide;
        });
    </script>
    

    Where is the appropriate place in my View markup, to place the script? Is there a better way I can reference IsReccuring checkbox, rather then knowing what Id it's going to have in advance?