Skip to content
Advertisement

Check checkbox using core JavaScript and event handler

I am working on the below demo. How can I add an event listener and handler to a #checker button to check the checkbox with the value of Benz using core JavaScript?

function checkBenz(){

}

var el = document.getElementById("checker");
el.addEventListener("click", checkBenz);
<button id="checker">Check Benz</button> <br />
<input type="checkbox" name="cars" value="Benz"> Benz <br />
<input type="checkbox" name="cars" value="BMW"> BMW <br />

Advertisement

Answer

Checkbox has a checked property. Set it to true in order to check your checkbox with plain JavaScript.

function checkBenz(){
  var benz = document.querySelector('input[value="Benz"]');
  benz.checked = !benz.checked;
  //or simply benz.checked = true,  if you don't want to toggle
}

var el = document.getElementById("checker");
el.addEventListener("click", checkBenz);
<button id="checker">Check Benz</button> <br />
<input type="checkbox" name="cars" value="Benz"> Benz <br />
<input type="checkbox" name="cars" value="BMW"> BMW <br />
Advertisement