This is my code
$('select.more-search').each(function(i, e){
more_srch[i] = $(this).attr('name');
$('#'+more_srch[i]+' :selected').each(function(j, selected){
more_sel[i][j] = $(selected).val();
});
});
It shows error in console as
TypeError: more_sel[i] is undefined
How to remove this error?
asked Jul 14, 2015 at 7:50
ranjith
2091 gold badge3 silver badges15 bronze badges
1 Answer 1
You need to initialize more_sel[i] to an empty array before you can assign to elements.
$('select.more-search').each(function(i, e){
more_srch[i] = $(this).attr('name');
more_sel[i] = [];
$('#'+more_srch[i]+' :selected').each(function(j, selected){
more_sel[i][j] = $(selected).val();
});
});
Instead of using .each(), you could use .map():
$('select.more-search').each(function(i, e){
more_srch[i] = $(this).attr('name');
more_sel[i] = $('#'+more_srch[i]+' :selected').map(function(j, selected){
return $(selected).val();
}).get(); // use .get() to turn returned jQuery object into normal array
});
answered Jul 14, 2015 at 8:04
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-js
more_sel?