Find name of selected option using jQuery

前端 未结 4 896
囚心锁ツ
囚心锁ツ 2021-02-04 01:21

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         


        
4条回答
  •  长发绾君心
    2021-02-04 02:07

    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);
    });

提交回复
热议问题