Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change the innerHTML of a <form-check form-switch> element in js?

This is my html code:

<div class="form-check form-switch">
    <input class="form-check-input" type="checkbox" id="mySwitch" name="emp">
    <label class="form-check-label" for="mySwitch">EmpName</label>
</div>

This is my js:

var Switch = document.getElementById("mySwitch");
Switch.addEventListener("click",function(){
    if(Switch.value=="yes")
        Switch.innerHTML="EmpNo";
    else
        Switch.innerHTML="EmpName";
})

I don’t know why the text isn’t changing. Can you please help me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re selecting the <input> element, but the one containing the text is the <label> element next to the input.

const input = document.getElementById("mySwitch");
const label = input.nextElementSibling.

Listen for the change event on the input instead of click. The change event will be triggered whenever the input has been checked or unchecked and is more reliable for this case.

Then check the .checked property on the input to see of the checkbox has been checked or not. Instead of modifying the .innerHTML property, use .textContent to set the changed text.

input.addEventListener('change' function() {
  if (input.checked) {
    label.textContent = 'EmpNo';
  } else {
    label.textContent = 'EmpName';
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading