Monday, 16 September 2019

Trigger change event select using jquery

is there anyway i could trigger a change event on select box on page load and select a particular option.
Also the function executed by adding the trigger after binding the function to the event.

<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>

$(function(){
    $('.check').trigger('change'); //This event will fire the change event. 
    $('.check').change(function(){
      var data= $(this).val();
      alert(data);            
    });
});


Answers:
Use val() to change to the value (not the text) and trigger() to manually fire the event.
The change event handler must be declared before the trigger.
$('.check').change(function(){
  var data= $(this).val();
  alert(data);            
});

$('.check')
    .val('two')
    .trigger('change');



0 comments:

Post a Comment