0

I have a multiselect dropdown and when the users selects either individual items or by pressing ctrl or shift I would like to capture the items and store them in an array, which afterwards take each value in the array and do some other things with it. I have accomplished the first part which is this:

var selectValues = new Array();
$('#ddlBProduct').change(function () {
    selectValues = [];
    selectValues.push($(this).val());
    MyFunction();
});

function MyFunction(){
    $.each(selectValues, function () {
        var theitem = $('#' + this).html();
   });
}

no in that function MyFunction for some reason i keep getting all the values as 1 value instead of each individual on. What I am assuming is that the "individual" value in the array is actually a list of all of the selected option instead of separating them into the array. help?

EDIT: removing the

selectValues = [];

results in this:

["81"] 
["81"] 
["81", "102"] 
["81"] 
["81", "102"] 
["81", "102", "30"] 

and thats when selecting one option and pressing shift and selecting more items.

Andres
  • 2,013
  • 6
  • 42
  • 67

2 Answers2

0

Try this:

$('select').change(function () {
    var selected_options = $(this).parent().find('option:selected');
    myFunction($.map(selected_options, function (selected_option) { return selected_option.value; }));
});

function myFunction(selectValues){
    console.log(selectValues)
    $.each(selectValues, function () {        
        var theitem = $('#' + this).html();
    });
}

Fiddle

pdoherty926
  • 9,895
  • 4
  • 37
  • 68
0

Try

var selectValues = new Array();
$('#ddlBProduct').change(function () {
    selectValues = $(this).val();
    MyFunction();
});

function MyFunction(){
    $.each(selectValues, function(idx, val){
        console.log('value: ', val)
    })
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531