<...">

How do I catch the <select> change event using jQuery?

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

      

Let's say I want to do some processing according to the selected value.

+2


source to share


6 answers


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

      



+12


source


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

      

You might also need to consider this if the person doesn't change this setting, but just clicks on the dropdown and selects the same item:



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

      

+4


source


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

      

+2


source


The accepted answer is ok, but don't catch the changes made by the key (arrow keys or alphanumeric keys).

This is the best example:

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

      

+1


source


You can get the selected value and text simply:

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

      

0


source


Using an arrow function, it could be:

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

      

Replacing this

with event.currentTarget

.

0


source







All Articles