How to recover the value of multiple dropdownlists (only filled)

Asked

Viewed 274 times

2

How can I recover the value of several dropdown (only filled)

The function below does not work correctly. For example, if I select only the second combo has as output: ,2 It picks up the void as if it were selection. It has a way around it?

    $("div.container-fluid").on("change", "select.dropDown", function() {

 var selectData = [];

        $('select.dropDown option:selected').each(function(i, selected){
            var selectData[i] = $(selected).val();

        });
});

My html is like this:

<select class="dropDown" id="column_1">
                 <option value="" selected="" disabled="">Please select</option>
                            <option value="1">A</option>
                            <option value="2">B</option>
                            <option value="3">C</option>
                            <option value="4">D</option>
</select>

<select class="dropDown" id="column_2">
                 <option value="" selected="" disabled="">Please select</option>
                            <option value="1">A</option>
                            <option value="2">B</option>
                            <option value="3">C</option>
                            <option value="4">D</option>
</select>

1 answer

1


I think you want to use the .filter() whose function is to reduce an array to the elements that serve a given condition.

Your code could be like this:

$("div.container-fluid").on("change", "select.dropDown", function () {
    var selectedCombos = $('select.dropDown').filter(function () {
        return this.value;
    });
});

and if you want, instead of the element select the value itself in that array so you can use the .map() thus:

$("div.container-fluid").on("change", "select.dropDown", function () {
    var selectedValues = $('select.dropDown').filter(function () {
        return this.value;
    }).map(function(){
        return this.value;
    }).get();
});

jsFiddle: http://jsfiddle.net/wong62pn/

It is curious, and perhaps confusing, that both methods have return this.value;. In the first case it checks whether value exists if it does not remove the array element. In the second case (.map()) the value that the return gives what is replaced in the array.

  • Sergio, could you explain why you don’t use: . filter(Function(i, Selected) in the second option? Another question: the "Selected" parameter is the dropdown selection in this case?

  • @jQuery makes the iterated element available in two places. Kind of unnecessary but both the this and the select in case you use arguments (i, select) in the iterator function. I chose to use the this, but if you use (i, selected) is good anyway, even more according to the native javascript API. I answered your question?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.