1

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?

2
  • What exactly you need? Have you defined more_sel? Commented Jul 14, 2015 at 7:53
  • what are you trying to do here Commented Jul 14, 2015 at 7:57

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.