Find name of selected option using jQuery

半腔热情 提交于 2020-01-30 19:42:41

问题


I've made a jquery/ajax function that updates #courses, sending #fos's .val() and .text(), specifically of the one that is selected, like so:

$('#selling #fos').change(function() {
    $.post('/ajax/courses',
        {
            fos_id: $('#selling #fos').val(),
            name: $('#selling #fos :selected').text()
        },
    function(data) {
        $('#selling #courses').html(data);
    });
});

How do I extend this function so that it uses 'this', allowing me to reuse this function multiple times on the same page? I'm caught because you can't use name: $(this + ' :selected').text().


回答1:


This should work:

$("#"+$(this).attr("id")+" :selected")

it's not pretty but it does the trick :)

or this will work:

$(this).find(":selected").text()



回答2:


I think what you are looking for is .filter()

name: $(this).filter(':selected').text()

It will return empty string if it's not selected

Good luck!

Edit:

I didn't see that Brett had a space before ":selected" which means he is looking for a child. Stefanvds suggestion to use find() will work fine. filter() checks if the current dom is ":selected" while find() is going to look for the children on all levels. You could also use .children() if you know that the selected dom you are looking for is a direct child of "this" as it is a lot more efficient since you are only looking for one level of children.

name: $(this).children(':selected').text()



回答3:


Without jQuery

It's pretty simple to do this without jQuery. Inside of a change event listener, the selected option can be accessed using this.options[this.selectedIndex]. From there, you can access the value/text properties of the selected option element.

Example Here

var select = document.querySelector('#select');

select.addEventListener('change', function (e) {
    var selectedOption = this.options[this.selectedIndex];

    console.log(selectedOption.value);
});

var select = document.querySelector('#select');

select.addEventListener('change', function (e) {
    var selectedOption = this.options[this.selectedIndex];
    
    alert(selectedOption.value);
});
<select id="select">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select>



回答4:


You can also use jQuery's second argument (context) to avoid the unnecessary "filter", "find", "children" etc. This allows your selector to be something like:

$('select[name="myselect"]').on('change',function(){
    var selectedOptionName = $('option:selected',this).text();
    console.log(selectedOptionName);
});


来源:https://stackoverflow.com/questions/3742378/find-name-of-selected-option-using-jquery

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