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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -