tags:

views:

68

answers:

5

Hello,

I am new to JQuery. I have a select html element. I am trying to understand how to iterate through the options in the select element. I know how to do it with traditional javascript as shown here:

for (i=0; i<mySelect.options.length; i++)
  alert(mySelect.options[i].value);

However, I'm trying to learn about JQuery more. Can someone show me the best way to iterate through a collection using JQuery?

Thank you

+8  A: 

Depends on what you want to do.

  • If you just want to iterative over the collection you could use each.

  • If you want to iterate over the collection and apply a transform to each element (and get a new collection back) there is map.

  • If you just want to select a subset of your collection there is grep.

R0MANARMY
A: 

Try this:

$("#mySelect options").each(
    alert($(this).attr("value"));
)
Makram Saleh
A: 

This snippet will get all input elements, and for each of them, print its index in the collection of elements (index) and its value to the log.

$(":input").each( function(index) { console.log(index + " " + this.value);})
Hober
+1  A: 

i believe you can use the each function for this. See here

Rob
+1  A: 

First off: IMHO it's great that you learn the non-jQuery way. Watch out that you don't slip into the thinking that everything better using jQuery.

To the problem: If you have a DOM reference mySelect to the select then you can get a jQuery object of the options with $(mySelect).find("option"). The usual way to loop through them would be with jQuery's each method and an (anonymous) function:

$(mySelect).find("option").each(function() {
   alert(this.value);
})
RoToRa