dimanche 13 mai 2018

MVC Razor custom checkbox updating 'real' checkbox

I am a novice, so please bear with me here. I am working on a form in MVC and want to have a custom checkbox. I kind of find my way to get it working the way I want by:

  • hiding the form checkbox
  • keep using the label of the checkbox to display its purpose
  • inserting a html label and input in combination with a script to get the checkbox value relayed

The relevant section of my view looks as follows:

<div id="loginRememberMeArea" class="formCheckBoxArea col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-3 col-md-6 col-lg-offset-3 col-lg-6">
    @Html.CheckBoxFor(m => m.RememberMe, new { @id = "loginRememberMeField", @class = "formCheckBoxField" })
    <input id="loginRememberMeCheckBoxHelper" class="formCheckBoxHelper" type="checkbox" value="checkbox1" name="" />
    <label id="loginRememberMeCheckBox" class="formCheckBox" for="loginRememberMeCheckBoxHelper"></label>
    @Html.LabelFor(m => m.RememberMe, new { @id = "loginRememberMeLabel", @class = "formCheckBoxLabel" })
</div>

And I am using this script to do the 'magic':

<script>
    $(document).ready(function () {
        $("input[type='checkbox']").bind('click', function () {
            var $t = $(this),
                val = $t.val(),
                key = val.charAt(val.length - 1);
            if ($t.val() == 'checkbox'+key && $t.is(':checked')) {
                $("#loginRememberMeField").attr('checked', true);
            }
            else {
                $("#loginRememberMeField").attr('checked', false);
            }
        });
    });
</script>

Now, this appears to work seamlessly: when I check the 'fake' checkbox, the script would make sure to check the 'real' checkbox (#loginRememberMeField) as well. It also works the opposite way, when unchecking the 'fake' checkbox, it would update the 'real' checkbox. And then it breaks: When re-selecting the checkbox for a second time, the 'real' checkbox would not be updated. I can't seem to find out why. Thank you in advance for your help!




Aucun commentaire:

Enregistrer un commentaire