简体   繁体   中英

Bind event on select option

I have the following HTML

<select>
  <option value="">filter</option>
  <option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
  <option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>

and I need to fire up a Javascript callback when any of the options is selected.

I have the following piece of Javascript:

$(function() {
   $(document).on("EVENT", "[data-behavior~=toggle-visibility]", function() {
   ...
  });
});

Is there an event I can use to achieve my goal?

PS - I understand I could move data-behavior="toggle-visibility" to the select tag and then listen for change and get the currently selected value. However, since that piece of Javascript is already used with other elements, I need to keep the data-behavior attribute on the option s.

It should work here https://jsfiddle.net/xpvt214o/535895/

You should be using on change event instead:

The example is as follows:

 $("select").on("change", function(e) { var sel = $(this).find(":selected"); var attr = sel.attr("data-behavior"); console.log(attr + "....." + $(this).val()) });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="">filter</option> <option data-behavior="toggle-visibility" data-scope="a" value="a">a</option> <option data-behavior="toggle-visibility" data-scope="b" value="b">b</option> </select>

Html Code:

<select id="maker-list">
  <option value="">filter</option>
  <option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
  <option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>

JavaScript code:

$('#maker-list').off('change').on('change', e => {
  
  selectedValue = $('#maker-list').val();
  // Here you can call another function with selectedValue
});

In above JavaScript Code, we bind change even and unbind the same event after selecting value so that it will not fire twice. jquery help

I hope this will work ... happy coding :)

 $("select").on("change", (e) => { console.log(e.target.value) })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="">filter</option> <option data-behavior="toggle-visibility" data-scope="a" value="a">a</option> <option data-behavior="toggle-visibility" data-scope="b" value="b">b</option> </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM