I am trying to change a part of my html code with JavaScript, but I can't get it to work:
function trigger(){ document.getElementById('mycheckbox').innerHTML="<input type="checkbox" id="mycheckbox" checked>"; } function triggerOff(){ document.getElementById('mycheckbox').innerHTML="<input type="checkbox" id="mycheckbox">"; }
<input type="checkbox" id="mycheckbox"> <button type="button" onclick="trigger()">test</button> <button type="button" onclick="triggerOff()">test</button>
So if I press the button I want to add the checked status to my HTML and if I press the other button I want to remove the checked status. Is this even possible?
All help is highly appreciated ! Thanks a lot guys!
Use checked
property, like this:
function trigger(){ document.getElementById('mycheckbox').checked=true; } function triggerOff(){ document.getElementById('mycheckbox').checked=false; }
<input type="checkbox" id="mycheckbox"> <button type="button" onclick="trigger()">test</button> <button type="button" onclick="triggerOff()">test</button>
Just do it like that
function trigger(){
document.getElementById('mycheckbox').checked = true;
}
function triggerOff(){
document.getElementById('mycheckbox').checked = false;
}
The innerHTML property will create inside your mycheckbox
another input
element
You cannot set innerHTML
to input type checkbox
. Use the checked
property to check/uncheck the checkbox
function trigger(){ document.getElementById('mycheckbox').checked = true; } function triggerOff(){ document.getElementById('mycheckbox').checked = false; }
<input type="checkbox" id="mycheckbox"> <button type="button" onclick="trigger()">test</button> <button type="button" onclick="triggerOff()">test</button>
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.