How to know the number of selected in option

This is the HTML

<select>
  <option value="1">test 1</option>
  <option value="2">test 2</option>
  <option value="3">test 3</option>
  <option value="4" selected="selected">test 4</option>
</select>

How can I know the length/number of the option selected? In html the selected is in 3.

so far this is what I tried

$("select").on("change", function() {
  var td = $(this);
  $("div").on("click", function() {
    var x = $("select").find("option:selected").length;
    var y = $("select").find("option[value='"+x+"']").length;
    $("span").text(x);
    td.prop('selectedIndex',x);
  });
});

Upvotes: 0

Views: 102

Answers (2)

Milan Chheda
Milan Chheda

Reputation: 8249

You can use index() to get the selected option number.

You can use $(this).val() to get the selected value.

And you can use $(this).find("option:selected").text() to get the selected text.

$("select").on("change", function() {
  var valueSelected = $(this).val();
  var selectedText = $(this).find("option:selected").text();
  var getIndex = $(this).find("option:selected").index();
  console.log('Selected Value: ' + valueSelected);
  console.log('Selected text: ' + selectedText);
  console.log('Selected Index: ' + getIndex)
});

$('div').on('click', function() {
  $('select').trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="1">test 1</option>
  <option value="2">test 2</option>
  <option value="3">test 3</option>
  <option value="4" selected="selected">test 4</option>
</select>
<div>
  Click me
</div>

Upvotes: 1

If you want to get the number of the selected, aka in your example, option 4 = number 3. then use the following.

$("div").on("click", function() {
  var td = $("select");
  var selected = td.find("option:selected")
  var x = td.find("option").index(selected);
  $("span").text(x);
});

This will use index() to get that result.

$("div").on("click", function() {
  var td = $("select");
  var selected = td.find("option:selected")
  var x = td.find("option").index(selected);
  $("span").text(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="1">test 1</option>
  <option value="2">test 2</option>
  <option value="3">test 3</option>
  <option value="4" selected="selected">test 4</option>
</select>
<div>
  wewewewewew
</div>
<span></span>

Upvotes: 1

Related Questions