JQuery - Iterating a Collection

I am new to JQuery. I have a select html element. I am trying to figure out how to iterate over the options in a select element. I know how to do it with regular javascript as shown here:

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

      

However, I am trying to learn more about JQuery. Can anyone show me a better way to iterate through a collection using JQuery?

thanks

+2


a source to share


5 answers


First: IMHO, it's great that you learn the non-jQuery way. Make sure you don't slip into the idea that jQuery is better for everything.

To the problem: If you have a DOM reference mySelect

to select

, then you can get the jQuery object option

using $(mySelect).find("option")

. The usual way to scroll through them is with a jQuery method each

and an (anonymous) function:



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

      

+1


a source


Depends on what you want to do.



  • If you just want to iterate over the collection, you can use each .

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

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

+9


a source


Try the following:

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

      

+1


a source


I believe you can use every function to do this. See here

+1


a source


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

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

      

0


a source







All Articles