[jquery] 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>

This question is related to jquery html select input

The answer is


Adding this piece of code after the val() seems to work:

$(":input#single").trigger('change');

I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.

So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below. The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.

Here's the code i use:

(function ($) {
    var originalVal = $.fn.val;
    $.fn.val = function (value) {
        if (arguments.length >= 1) {
            // setter invoked, do processing
            return originalVal.call(this, value).trigger('change');
        }
        //getter invoked do processing
        return originalVal.call(this);
    };
})(jQuery);

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.


$(":input#single").trigger('change');

This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this

$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');

And the first event worked.


In case you don't want to mix up with default change event you can provide your custom event

$('input.test').on('value_changed', function(e){
    console.log('value changed to '+$(this).val());
});

to trigger the event on value set, you can do

$('input.test').val('I am a new value').trigger('value_changed');

If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:

window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);

To make it easier add a custom function and call it when ever you want that changing the value also trigger change

$.fn.valAndTrigger = function (element) {
    return $(this).val(element).trigger('change');
}

and

$("#sample").valAndTirgger("NewValue");

Or you can override the val function to always call the change when the val is called

(function ($) {
    var originalVal = $.fn.val;
    $.fn.val = function (value) {
        this.trigger("change");
        return originalVal.call(this, value);
    };
})(jQuery);

Sample at http://jsfiddle.net/r60bfkub/


As far as I can read in API's. The event is only fired when the user clicks on an option.

http://api.jquery.com/change/

For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?