How to catch the event of change of <select > with jQuery?
-
05-07-2019 - |
Question
<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.
Solution
$('#target').change( function() {
$(this).find(":selected").each(function () {
console.log( $(this).val() );
});
});
OTHER TIPS
$("#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());
});
$("#target").change( function() {
var selectedOption = $("#target option:selected");
var selectedValue = selectedOption.val(); // gets the selected value
var selectedText = selectedOption.text(); // gets the selected text
});
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
});
});
You can get the selected value and text simply by:
$("#target").change(function() {
var selectedValue = $(this).val(),
selectedText = $('option:selected', this).text();
// ...
});
Using arrow-function, it can be :
$('#target').change((e) =>{
console.log(e.currentTarget.value);
console.log(e.currentTarget.textContent);
});
Replacing this
by event.currentTarget
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow