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
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.
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With