Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 976
dieuvn3b Avatar asked Dec 08 '15 08:12

dieuvn3b


2 Answers

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")
}
like image 52
gurvinder372 Avatar answered Oct 10 '22 02:10

gurvinder372


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();

like image 26
Jai Avatar answered Oct 10 '22 04:10

Jai