Search code examples
javascriptjqueryjquery-selectorsselect-options

Issues with Select Option loop with jQuery


I am using jQuery to loop through many Select Option html elements, and I can get it to work one at a time, but I'm having difficulty accessing the data if it is stored in a jQuery element.

For example I have these 2 Select html elements

var lList = $(".p1_lSelect");

var rList = $(".p1_rSelect");

I can get my desired output with the following

$(".p1_lSelect option:selected").each(function() {
    selected = $(this).text(); //selected == "p1_lSelect_Data"
    console.log(selected);
});

$(".p1_rSelect option:selected").each(function() {
    selected = $(this).text(); //selected == "p1_rSelect_Data"
    console.log(selected);
});

//Console logs .p1_lSelect_Data and .p1_rSelect_Data as expected

What I would like is something similar to the following so that I can change which list I'm feeding into the loop

function foo(){
    var lList = $(".p1_lSelect");
    var rList = $(".p1_rSelect");
    bar(lList);
    bar(rList);
}

function bar(list){
    $("list option:selected").each(function() {
        selected = $(this).text();
        console.log(selected);
    });
    //Console log does not print
}

How would I go about doing this?


Solution

  • Please try following code based on your structure:

    function foo(){
        var lList = $(".p1_lSelect");
        var rList = $(".p1_rSelect");
        bar(lList);
        bar(rList);
    }
    
    function bar(list){
        $(list).find("option:selected").each(function() {
            selected = $(this).text();
            console.log(selected);
        });
        //Console log does not print
    }