1. ホーム
  2. jquery

[解決済み] Trigger change event <select> using jquery

2022-04-22 08:27:19

Question

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.

I was trying to output something like this

<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);            
    });
});

http://jsfiddle.net/v7QWd/1/

How to solved?

Use val() to change to the value (not the text) and trigger() to manually fire the event.

変更イベントハンドラは、トリガーの前に宣言する必要があります。

以下はサンプルです。

$('.check').change(function(){
  var data= $(this).val();
  alert(data);            
});

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