简体   繁体   中英

checkbox on checked state changes header text

<input type="checkbox" id="chk">
<label for="chk"></label>
<h1 id="header">Lorem ipsum</h1>
var chk = document.querySelector('#chk');
var header = document.querySelector('#header');
if(chk.checked)
    header.innerHTML = "state 1";
else
    header.innerHTML = "Lorem ipsum";

So. when checkbox is checked text in changes to "state 1" when unchecked(default state) text returns to "state 2". This code isnt working what i want

Hi Bro!

<input type="checkbox" id="chk"> <label for="chk"></> <h1 id="header">Lorem ipsum</h1>

`

var chk = document.querySelector('#chk');
var header = document.querySelector('#header');

chk.addEventListener('change', function (e) {
    if(chk.checked)
        header.innerHTML = "state 1";
    else
        header.innerHTML = "state 2";
});

`

Here's a simple solution. Hope it helps!

 function myFunction(mycheckbox, label) { document.getElementById(label).innerHTML = mycheckbox.checked ? "state 1" : "state 2"; } 
 <input type="checkbox" onclick="myFunction(this, 'header');" /> <label for="chk" id="header">Lorem ipsum</label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM