admin管理员组

文章数量:1341746

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>

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!

Share Improve this question edited Oct 24, 2018 at 14:03 Mamun 69k9 gold badges51 silver badges62 bronze badges asked Oct 24, 2018 at 13:18 pozapoza 2651 gold badge3 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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>

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

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>

本文标签: htmlChange checkbox checked with JavaScriptStack Overflow