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 :)
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.
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.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With