Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox onchange event not firing

I have the following setup: 2 checkboxes such that when the first is checked, it toggles the state of the second one. The second one has an onchange listener which is supposed to trigger an alert when it changes.

Problem is, when I click on it, the onchange is fired alright, but when I use the first to change it's state, the event isn't fired.

I'm I missing something? or is the onchange event basically meant to act like an onclick?

<!DOCTYPE html>
<html>
<body>

  <form action="">
    <input id='one' type="checkbox" name="vehicle" value="Bike">I have a bike<br>
    <input id='two' type="checkbox" name="vehicle" value="Car" checked>I have a car 
  </form>
  <script>
    function show(){
      alert(document.getElementById('two').checked);
    }

    document.getElementById('one').addEventListener('click', function(){
      var two = document.getElementById('two');
      two.checked = ! two.checked;
    });

    document.getElementById('two').addEventListener('change', function(){
      alert("changed");
    });
  </script>

</body>
</html>

Thanks for helping :)

like image 449
SamAko Avatar asked May 27 '15 16:05

SamAko


People also ask

Does Onchange work for checkbox?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

How does Onchange work?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

How do I stop Onchange events?

preventDefault(); only prevent the default action of the control. change event is not the default action for textbox. Thank anyway. In the above code if the textbox is empty the server side event will not be fired else it will get fired.


1 Answers

You are changing an attribute, that will not make the event fire, you can either trigger the change event, or instead click the second checkbox.

Try changing:

document.getElementById('one').addEventListener('click', function(){
  var two = document.getElementById('two');
  two.checked = ! two.checked;
});

To:

document.getElementById('one').addEventListener('click', function(){
  document.getElementById('two').click()
});

Another solution would be triggering the change event:

document.getElementById('one').addEventListener('click', function(){
  var two = document.getElementById('two');
  two.checked = ! two.checked;
  two.dispatchEvent('change');
});
like image 170
taxicala Avatar answered Sep 20 '22 23:09

taxicala