This is my html
code:
<div >
<input type="checkbox" id="mySwitch" name="emp">
<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?
CodePudding user response:
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';
}
});