How to fire JQuery change event when input value changed programmatically?

前端 未结 5 2045
时光说笑
时光说笑 2020-12-10 10:23

I want to fire the JQuery change event when the input text is changed programmatically, for example like this:

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 10:44

    What you need to do is trigger the change event after you've set the text. So you may create a function to do that so you won't have to repeat it every time you need to update the text, like this:

    function changeTextProgrammatically(value) {
        $("input").val( value );
        $("input").trigger( 'change' ); // Triggers the change event
    }
    
    changeTextProgrammatically( "A" );
    

    I've updated the fiddle,

提交回复
热议问题