javascriptjqueryjquery-trigger

execute a change event on input that was modified by another function


I have a function that does a calculation on an input, I have a function in another script I want to run when the value of the input changes.

I try to do with the change event but does not register the change unless you change the value myself.

$(document).ready(
function(){
    $("#hello").val(1+1);
    $("#hello").change( function(){
        alert("change");
        }
    );
});

the solution I found was

$(document).ready(
function(){
    $("#hello").val(1+1).trigger('change');
    $("#hello").change( function(){
        alert("change");
        }
    );} );

Solution

  • I think you should be attaching the event first & then make the change. Don't you?

    Besides you might have to fire the event manually (using .trigger), like this:

    $(document).ready(function(){
    
       $(".hello").change( function(){ alert("change"); });
    
       $(".hello").val(1+1).trigger("change");
    
    });