I have the following HTML code :
<select name="test123" id="test123" onchange="testOnchange()">
<option>Chocolate</option>
<option>Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<script>
$( "#test123" ).change(function() {
console.log("change");
});
function testOnchange() {
console.log("onchange");
}
</script>
If I use JS to set a value for the select like this:
$("#test123").val("Candy");
why does testOnchange()
trigger, but jQuery change
doesn't?
What exactly is the difference between change
and onchange
?
It is because you didn't ensured that <select>
is loaded in dom before binding the change
event, check this fiddle
and check this fiddle again when these scripts were wrapped inside onload
event of the document
.
Also, if you are setting the value programmatically, you need to trigger the change() event programmatically as well, check here and here
$( document ).ready( function(){
$( "#test123" ).change(function () {
console.log("change");
});
});
function testOnchange(){
console.log("onchange")
}
why does testOnchange() trigger, but jQuery change not?
This is because onchange
is an event defined in DOM api but .change
is from jQuery
's event object.
So, although when you apply a change event with jQuery code $("#test123").val("Candy")
it causes a change event in DOM so the native one is fired only.
In case if you want to trigger the jQuery
's change
event too, then you need to trigger it manually as the other answer suggested. $("#test123").val("Candy").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