array iteration in jquery -
this 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 typeerror: more_sel[i] undefined
how remove error?
you need initialize more_sel[i]
empty array before can assign 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()
, 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() turn returned jquery object normal array });
Comments
Post a Comment