3

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!

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answers! I know that I could do it with .checked= true/false. But I was trying to get the change persistant. So If I reload the page the checked is still there. I don't want to do it with local storage.
3

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

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.