Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  152] [ 7]  / answers: 1 / hits: 16506  / 9 Years ago, tue, december 8, 2015, 12:00:00

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?


More From » jquery

 Answers
7

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

[#64134] Friday, December 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
angelicajayleneh

Total Points: 216
Total Questions: 110
Total Answers: 100

Location: Sudan
Member since Tue, Aug 3, 2021
3 Years ago
;