How to catch the event of change of <select > with jQuery?

拈花ヽ惹草 提交于 2019-12-24 03:03:42

问题


<select id="target">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
</select>

Say,I want to do some processing according to selected value.


回答1:


$('#target').change( function() {
   $(this).find(":selected").each(function () {
            console.log( $(this).val() );
    });
 });



回答2:


$("#target").change( function() {
    alert($("#target option:selected").val());
});

You may also need to consider this as well if the person does not change the option, but simply clicks on the drop down and selects the same item:

$("#target option").click( function() {
     alert($("#target option:selected").val());
});



回答3:


$("#target").change( function() {
  var selectedOption = $("#target option:selected");
  var selectedValue = selectedOption.val();  // gets the selected value
  var selectedText = selectedOption.text();  // gets the selected text
});



回答4:


The accepted answer is okay but do not catch changes done by keypress (arrow-keys or alphanum keys).

This is a better apporach:

$('#target').bind("change keyup",function() {
   $(this).find(":selected").each(function () {
     // do something amazing here
   });
});



回答5:


You can get the selected value and text simply by:

$("#target").change(function() {
  var selectedValue = $(this).val(),
      selectedText = $('option:selected', this).text();
  // ...
});



回答6:


Using arrow-function, it can be :

$('#target').change((e) =>{
        console.log(e.currentTarget.value);
        console.log(e.currentTarget.textContent);
 });

Replacing this by event.currentTarget .



来源:https://stackoverflow.com/questions/1403297/how-to-catch-the-event-of-change-of-select-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!