简体   繁体   中英

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 :)

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');
});

If the goal is to have only one checkbox checked, here is a jQuery solution:

$(document).ready(function () {

    $('#one, #two').change(function (e) {
        if ($(this).prop('checked')) {
            $('#one, #two').not(this).prop('checked', false)
        }
    });

});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM