Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  174] [ 5]  / answers: 1 / hits: 8354  / 9 Years ago, wed, may 27, 2015, 12:00:00

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


More From » jquery

 Answers
8

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

[#36828] Tuesday, May 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyreek

Total Points: 421
Total Questions: 115
Total Answers: 102

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;