Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the jquery change event not trigger when I set the value of a select using val()?

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?

<select id="single">     <option>Single</option>     <option>Single2</option> </select>  <script>     $(function() {         $(":input#single").change(function() {            /* Logic here does not execute when val() is used */         });     });      $("#single").val("Single2"); </script> 
like image 364
Eric Belair Avatar asked Jan 12 '11 18:01

Eric Belair


People also ask

Does jQuery Val trigger change event?

When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.

What is $( This val () in jQuery?

The val() method is an inbuilt method in jQuery which is used to returns or set the value of attribute for the selected elements. This method apply on the HTML form elements. Syntax: There are three ways to use this method which are given below: $(selector).val()

How do you trigger an event on dropdown change?

$(document). ready(function(){ $('#countrylist'). change(function(e){ // Your event handler }); // And now fire change event when the DOM is ready $('#countrylist'). trigger('change'); });


2 Answers

Because the change event requires an actual browser event initiated by the user instead of via javascript code.

Do this instead:

$("#single").val("Single2").trigger('change'); 

or

$("#single").val("Single2").change(); 
like image 58
user113716 Avatar answered Sep 18 '22 03:09

user113716


I believe you can manually trigger the change event with trigger():

$("#single").val("Single2").trigger('change'); 

Though why it doesn't fire automatically, I have no idea.

like image 35
David Thomas Avatar answered Sep 21 '22 03:09

David Thomas