2016-10-04 29 views
1

私はselect要素とbuttonを持っています。選択肢が他の方法から変更された場合、JavaScript onchangeイベントは発生しません

select要素からオプションを変更した

は、それはいくつかの機能を呼び起こす:

<select id="mySel" onchange="someFunction();"> 
    <option value="1">Option 1</option> 
    <option value="2">Option 2</option> 
    ... 
</select> 

<input type="button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;"/> 

someFunction()

私はselect要素自体からオプションを変更したとき、私はボタンをクリックしないとき喚起だけさ。

私がしようとしているのは、オプションが変更されている場所に関係なく、選択要素onchangeイベントを発生させることです。

ボタンのonclickイベントにsomeFunction()を追加することができますが、それは私が探しているものではありません。

アイデアをお寄せいただきありがとうございます。

+0

http://stackoverflow.com/questions/2490825/how- to-trigger-in-javascript – Tschallacka

+0

http://stackoverflow.com/questions/4672505/why-does-the-jquery-change-event-not-trigger-when-i-set-the-value-of- a-select-us –

答えて

2

あなたは、イベントリスナーを追加することができますタグを使用して、よりクリーンなコードを提供します。

実行この例で、それが役に立てば幸い:

// Wait for WINDOW LOAD 
 
window.onload = function() { 
 
    // - Bind onchange event listener to the <select> DOMNode 
 
    // - Your "someFunction" function is fired here! 
 
    document.getElementById('mySel').addEventListener('change', someFunction); 
 
    
 
    // Trigger the change from the '#your_button' click callback 
 
    document.getElementById('your_button').addEventListener("click", function() { 
 
    // Create a new 'change' event 
 
    var event = new Event('change'); 
 
    // Dispatch it 
 
    document.getElementById('mySel').dispatchEvent(event); 
 
    }); 
 
} 
 

 
// Your function - Look at the console 
 
function someFunction() { 
 
    console.log('here!'); 
 
}
<select id="mySel"> 
 
    <option value="1">Option 1</option> 
 
    <option value="2">Option 2</option> 
 
</select> 
 

 
<input type="button" id="your_button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;"/>

あなたはで詳細を見ることができます:Select Tag Change Event Call on Selected Index Change

1

あなたのボタンhtmlを変更してください。

<input type="button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;someFunction();"/> 

また、コメント内の前述のリンクごとに手動で変更イベントをトリガーします。

+0

これは私が探しているのではない...私はユーザーがselect要素自体とは異なるオプションを設定せずにonchangeイベントを発生させることができるかどうかを知りたい –

+0

selectedIndexの値をプログラム的に変更しても、onchangeイベントは発生しません。これはWindowsアプリケーションで起こりますが、html/javascriptではこのイベントを手動でトリガーする必要があります。 –

0

これを使用すると、必要なものを手に入れることができます。 DOMがロードされたら、イベントコールバックにそれは「プログラム的に」発射だ毎回それぞれの要素の内部には、「イベントの呼び出し」を取得しますSOUとき

function someFunction(select){ 
 
    console.log('reached here'); 
 
    
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> 
 
<select id="mySel" onchange="someFunction();"> 
 
    <option value="1">Option 1</option> 
 
    <option value="2">Option 2</option> 
 
    ... 
 
</select> 
 

 
<input type="button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;someFunction();"/>

+0

私が探しているものではありません...ボタンにその関数を呼び出させたくありません。 –

関連する問題