jquery select change event get selected option

2019-01-03 12:36发布

I bound an event on the change event of my select elements with this:

$('select').on('change', '', function (e) {

});

How can I access the element which got selected when the change event occurs?

标签: jquery events
7条回答
甜甜的少女心
2楼-- · 2019-01-03 13:04

I find this shorter and cleaner. Besides, you can iterate through selected items if there are more than one;

$('select').on('change', function () {
     var selectedValue = this.selectedOptions[0].value;
     var selectedText  = this.selectedOptions[0].text;
});
查看更多
姐就是有狂的资本
3楼-- · 2019-01-03 13:07

Delegated Alternative

In case anyone is using the delegated approach for their listener, use e.target (it will refer to the select element).

$('#myform').on('change', 'select', function (e) {
    var val = $(e.target).val();
    var text = $(e.target).find("option:selected").text(); //only time the find is required
    var name = $(e.target).attr('name');
}

JSFiddle Demo

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-03 13:16

You can use the jQuery find method

 $('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
 });

The above solution works perfectly but I choose to add the following code for them willing to get the clicked option. It allows you get the selected option even when this select value has not changed. (Tested with Mozilla only)

    $('select').find('option').click(function () {
     var optionSelected = $(this);
     var valueSelected  = optionSelected.val();
     var textSelected   = optionSelected.text();
   });
查看更多
5楼-- · 2019-01-03 13:20
<select id="selectId">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>


$('#selectId').on('change', function () {
     var selectVal = $("#selectId option:selected").val();
});

First create a select option. After that using jquery you can get current selected value when user change select option value.

查看更多
Deceive 欺骗
6楼-- · 2019-01-03 13:25
$('#_SelectID').change(function () {
        var SelectedText = $('option:selected',this).text();
        var SelectedValue = $('option:selected',this).val();
});
查看更多
趁早两清
7楼-- · 2019-01-03 13:27

Another and short way to get value of selected value,

$('#selectElement').on('change',function(){
   var selectedVal = $(this).val();
                       ^^^^  ^^^^ -> presents #selectElement selected value 
                         |
                         v
               presents #selectElement, 
});
查看更多
登录 后发表回答