James Franco
James Franco

Reputation: 4706

Understanding the each jquery function - Unexpected output

I am trying to wrap my head around the each function. In this fiddle here I would like to iterate through the selected elements of the list box one by one.

Essentially I was expecting an output like this

found itemA
found itemB

However I get an output like this

found itemA,itemB

I would like to know why that is happening and how I can fix it. This is the code I am using

HTML

<select multiple="multiple" size="5" id="test">
    <option>itemA</option>
    <option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>

JQuery

$( "#bid" ).click(function() {
   $("#test").each(function () {
       console.log("found " + $(this).val());
   });           
});

Upvotes: 1

Views: 61

Answers (4)

kind user
kind user

Reputation: 41893

  • You have to specify the elements selector. Using only #test won't iterate over options because you didn't actually refer to it.

$("#bid").click(function() {
  $("#test option").each(function() {
    console.log("found " + $(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" size="5" id="test">
  <option>itemA</option>
  <option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>

Upvotes: 2

Twisty
Twisty

Reputation: 30893

Here is an example that might explain it more: https://jsfiddle.net/Twisty/dr1tay6f/6/

HTML

<select multiple="multiple" size="5" id="test">
  <option value="a">Item A</option>
  <option value="b">Item B</option>
</select>
<br>
<button type="button" id="bid">test</button>

JavaScript

$(function() {
  $("#bid").click(function() {
    $("#test option").each(function(ind, el) {
      console.log("At Index " + ind +" found Option with Value: " + $(el).val() + " and Label of: " + $(el).html());
    });
  });
});

The $(selector).each(callback(index, element)); will iterate over each element in the selector, passing it's index and element to the function.

Upvotes: 0

Bergi
Bergi

Reputation: 664538

You'll want to use

$.each($("#test").prop("options"), function () {
    console.log("found " + this.value);
});

or

$("#test").children().each(function () {
    console.log("found " + this.value);
});

Upvotes: 1

Charlie
Charlie

Reputation: 9108

You are iterating over the select and not the options. The function you passed to each is getting called just once. Change your selector to #test > option and, like the comments on the question, change val() to text().

$( "#bid" ).click(function() {
   $("#test > option").each(function () {
       console.log("found " + $(this).text());
   });           
});

Upvotes: 2

Related Questions