user70192
user70192

Reputation: 14204

JQuery - Collection Iteration

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

Upvotes: 3

Views: 3278

Answers (5)

Makram Saleh
Makram Saleh

Reputation: 8701

Try this:

$("#mySelect options").each(function()
{
    alert($(this).attr("value"));
})

Upvotes: 1

RoToRa
RoToRa

Reputation: 38390

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);
})

Upvotes: 2

Rob
Rob

Reputation: 6871

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

Upvotes: 1

bsberry
bsberry

Reputation: 1008

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);})

Upvotes: 0

Roman
Roman

Reputation: 20246

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.

Upvotes: 9

Related Questions