jQuery .trigger(); Method
.trigger()
method can easily click or change an element. They can be fired manually, with the .trigger()
. A call to .trigger()
executes the handlers in the same order they would be if the event were triggered naturally by the user.
If an JQuey event or Ajax is defined in an element click or change. If you want to activate that element’s events in any other element click or change, you can follow the example given below.
Example 1:
<button type="button" id="element1">Element 1</button>
<button type="button" id="element2">Element 2</button>
<script type="text/javascript">
$( function() {
$( "#element1" ).on( "click", function() {
alert( "Hello!!" );
} );
$( "#element2" ).on( "click", function() {
$( "#element1" ).trigger( "click" );
} );
} );
</script>
Example 2:
<input type="text" id="element1" name="element1">
<button type="button" id="element2">Element 2</button>
<script type="text/javascript">
$( function() {
$( "#element1" ).on( "change", function() {
if ( $( "#element1" ).val() == "test" ) {
alert( "Hello!!" );
}
} );
$( "#element2" ).on( "click", function() {
$( "#element1" ).val( "test" ).trigger( "change" );
} );
} );
</script>