jeudi 18 juin 2020

How to read checked state of toggle switch (checkbox) using javascript when Razor page loads

I have a Razor page with a Bootstrap 4.3.1 Toggle Switch checkbox. It is bound to the Razor Page Model and works fine. I also have a javascript function that changes the label depending if the state is checked or not.

What I want to be able to do is have the label change to the correct one for checked/not checked when the page loads.

My code for creating the checkbox with a HTML.CheckBoxFor is below:

               <div class="form-group custom-switch">
                    @Html.CheckBoxFor(Model => Model.ExistingCase.Closed, new {@class= "custom-control-input", @onclick="caseClosed(this)" })
                    <label class="custom-control-label" id="lblCaseClosed" for="ExistingCase_Closed">Slide right to Close Case</label>
                </div>

This creates the HTML page output as follows:

                <div class="form-group custom-switch">
                    <input checked="checked" class="custom-control-input" data-val="true" data-val-required="The Closed field is required." id="ExistingCase_Closed" name="ExistingCase.Closed" onclick="caseClosed(this)" type="checkbox" value="true" />
                    <label class="custom-control-label" id="lblCaseClosed" for="ExistingCase_Closed">Slide right to Close Case</label>
                </div>

It works fine...

Then I have some Javascript that is trigged by the change in the checkbox (toggle) and changes the associated label text "Slide right to Close Case" depending on the state of the checkbox (toggle). That script is as follows:

       function caseClosed(el) {
            document.getElementById('lblCaseClosed').innerHTML = el.checked ? "Case is Closed" : "Case is Open"
            }

This too works fine.

What I cannot do is have the label text read "Case is Closed" or "Case is Open" when the page first loads. I'm new to Razor and Javascript - so I'm hoping that there is a simple 'onload' type event that can read the 'checked' state of the toggle (checkbox) and set the correct text in the label.

Sorry if this is wordy but difficult to explain. Here is what the states of the toggle switch (checkbox) looks like when I load the page. But the other two are when I change the state on the page with the mouse.


Here is what it looks like when I load the page now. This is what I slide the toggle off. This is what I slide the toggle on.





Aucun commentaire:

Enregistrer un commentaire