Anas Jah
Anas Jah

Reputation: 1

Do an action when check box is checked or unchecked

I'm making a form in html, one element of the form is checkbox asks the user if he has a phonenumber, and I'm trying to make two action: if the checkbox is checked I want a new input element appear in the same page to let the user enter his phone number, and if the user change his mind and try to uncheck the checkbox the last input removed and another input appear for another information. It works with me when the checkbox is checked and the input appear to let the user enter his number, but if the user changed his mind or checked this checkbox by a mistake and uncheck it, the input of the number still in the page, I mean that the uncheck event in the checkbox is not working after it's checked! Any help please ...

<html>
<head><script>
function change(n){
if (n.checked)
document.getElementById("message").innerHTML = "enter your number <input type="text" ....";
if (n.unchecked)
document.getElementById("message").innerHTML = "age <input type="text" ....";
}
</script>
</head>
<body><label><input type = "checkbox" onchange = "change(this)">Checkbox</label>
<div id="message"></div>
</body>

Upvotes: 0

Views: 1129

Answers (1)

Rishabh
Rishabh

Reputation: 2021

You just need an if..else on the this.checked value. So something like this -

document.querySelector('input[type="checkbox"]').addEventListener('change', function () {
    if (this.checked) {
        document.getElementById("message").innerHTML = 'enter your number <input type="text">';
    }
    else {
        document.getElementById("message").innerHTML = 'age <input type="text">';
    }
}, false);

Working Demo

Upvotes: 1

Related Questions