What is the difference between jQuery change and onchange of HTML?

dieuvn3b picture dieuvn3b · Dec 8, 2015 · Viewed 11.5k times · Source

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?

Answer

gurvinder372 picture gurvinder372 · Dec 8, 2015

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")
}