简体   繁体   中英

HTML Select unable to get selected value data in javascript

Basically, my current code is to hide options from the dropdown of selected items. The below code is working when the user selects the option it will hide the selected value in all the dropdowns. But I facing one issue which is when I want to get all the selected value from the dropbox box it will return a null value when the save button trigger. Anyone can help with this, I stuck in this issue long time:((?

在此处输入图像描述

Source Code: https://jsfiddle.net/8forcbg3/4/

$( ".firstname").on('change',function() {

            
 $(".firstname option").prop("disabled", false); //enable everything

            //collect the values from selected;
            var arr = $.map(
                        $(".firstname option:selected"), function (n) {
                            return n.value;
                        }
                    );

            //disable elements
            $(".firstname option").filter(function () {
                return $.inArray($(this).val(), arr) > -1; //if value is in the array of selected values
            }).prop("disabled", true);

            //re-enable elements
            $(".firstname option").filter(function () {
                return $.inArray($(this).val(), arr) == -1; //if value is not in the array of selected values
            }).prop("disabled",false);

            $(this).prop('disabled',false);//re-enable the current one //1
            $(this).show();//and show it //1
            $(this).prop('selected',true);//just to be sure re-select the option afterwards //1
           
        });
        
        
         $('.savebtn').on('click', function(){
         $('.cbb').each(function(index, item){
            var selectVal  = $(this).find('select').val();
                       
                        console.log(selectVal);
                        
                         });
         });
            
        

Here's Get selected value of a dropdown's item using jQuery
Get Selected value by like this,

 var selectVal  = $(this).find('select :selected').text(); 

The resolution for your question is this:

$('.savebtn').on('click', function(){
    $('.cbb').find('select option:selected').each(function(index, item){
        var selectVal = $(this).val();
        console.log(selectVal);
    });
});

You must use a selector :selected to get the current selected option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM