I need to assign an onclick event to a CheckBoxFor in ASP.NET MVC razor, but it is never called.
I have something like this, which does not work:
<script type="text/javascript">
    function setCompleteStatus() {
        alert("setCompleteStatus called");
    }
</script>
@Html.CheckBoxFor(m => m.Process.IsComplete, 
                  new Dictionary<string, object>{
                     {"id", "p1isCompleted"}, 
                     {"onclick","setCompleteStatus()"}, 
                     {"data-role", "flipswitch"}, 
                     {"data-on-text", "complete"}, 
                     {"data-off-text", "incomplete"}, 
                     {"data-wrapper-class", "custom-size-flipswitch"}})
This attempt also doesn't work:
<script type="text/javascript">
    $("#p1isCompleted").click(
        function setCompleteStatus() {
            alert("setCompleteStatus called");
        }
    );
</script>
This approach leads to the alert being called once when the page is loaded but not when I click on the checkbox:
<script type="text/javascript">
    $(document).ready(
        $("#p1isCompleted").click(
            alert("setCompleteStatus called");
        )
    );
</script>
Because of the data- attributes I cannot use a dictionary like this: new {@onclick, "setCompleteStatus('1')"}
By the way, there are no javascript errors displayed in Firefox's console
In MVC, use underscore(_) instead of Hyphen(-) for data* attributes
Just pass the html attributes parameter as anonymous object shown below for CheckBoxFor.
 @Html.CheckBoxFor(m => m.Process.IsComplete, 
              new {
                   @id="p1isCompleted", 
                   @onclick="setCompleteStatus()", 
                   @data_role="flipswitch",
                 }
                        You can do it by modify your {"onclick", "setCompleteStatus()"} code to {"onclick","setCompleteStatus.call(this)"} and get advantage of this variable. It should be like this:
@Html.CheckBoxFor(m => m.Process.IsComplete,
                  new Dictionary<string, object>{
                     {"id", "p1isCompleted"},
                     {"onclick","setCompleteStatus.call(this)"},
                     {"data-role", "flipswitch"},
                     {"data-on-text", "complete"},
                     {"data-off-text", "incomplete"},
                     {"data-wrapper-class", "custom-size-flipswitch"}})
<script type="text/javascript">
    function setCompleteStatus() {
        alert(this.checked);
    }
</script>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With