Link to home
Start Free TrialLog in
Avatar of Wanting2LearnMan
Wanting2LearnManFlag for United Kingdom of Great Britain and Northern Ireland

asked on

jquery selector question

I have a Html like so:

 <select id="myList" class="CustomSelect1">    
     <option value="0">MyOption1</option>	
     <option value="1">MyOption2</option>		
  </select>

Open in new window


In my associated javascript file I do the following:
var nic_list = $('#myList');

Open in new window


In my Firefox debugger I can see that when I expand out nic_list and see the option values MyOption1 and MyOption2.

How do I properly get these values and store them in an array?? (There can be any number of entries in the dropdown box)
SOLUTION
Avatar of YZlat
YZlat
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If I'm not mistaken you don't need the .each loop, as when a jQuery selector matches more than one element he already returns an array with all the matched elements.

So you can directly associate the result from your selector without having to iterate through it.
Bardobrave, where do you see .each loop?? I just assigned it to a variable
@Bardobrave - you are :)

Try your code - it just grabs the option text from the first option in the list. The question was specifically about how to store all options in an array, so you need to loop through the collection and add the text for each option to the array.

@YZlat - your code grabs the text for the selected option - not all of them.
Avatar of Wanting2LearnMan

ASKER

I used this:
var myArray = new Array();
$('#myList option').each(function() {
    myArray.push( $(this).text());
});

Thanks,

It does the trick.
But now since I have several rows in a html table all with a dropdown box, I end up with an array as follows:
myArray["MyOption1", "MyOption2", "MyOption1", "MyOption2", "MyOption1",
"MyOption2"]

Is there a way I can get only the contents of one of the dropdown boxes??

Thanks for all your help
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK I changed it so each one has a unique id :)