1

So i have a <select> with option, but what i want when i select a option to get the option number.

I do not want him to grab attributes(No value & text). Because it is dynamic.

Example:

<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>

When i select Apple, that I get a response 1. so with Pear: 2. and so on.

I have found: W3school, But this will show how many option are available.

What someone here a solution for?

3
  • 1
    Why don't you assign a value to each option? Which is the reason you don't want to do this? Commented Jun 15, 2017 at 21:08
  • The selectedIndex property contains the option number. Commented Jun 15, 2017 at 21:11
  • $('option:selected').index() Commented Jun 15, 2017 at 21:12

3 Answers 3

3

You can use the selectedIndex property of the <select>.

$("#mySelect").change(function() {
  console.log("Selected option is " + this.selectedIndex);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
  <option>Choose a fruit</option>
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>

Sign up to request clarification or add additional context in comments.

4 Comments

This one is perfect, because it start with 0. thanks you.
@jurdekker didn't you ask in your question to start with 1?
Yes, but sorry. i forgot it.
This starts with 1 because 0 is the option that means they didn't select anything. But if you get rid of that you can easily just add 1.
1

You could try something like this using plain JavaScript:

document.addEventListener('DOMContentLoaded', function(){
    var selectEle = document.getElementById('mySelect');
    selectEle.addEventListener('change', function(item){
        console.log(selectEle.selectedIndex + 1);
    });
});
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>

Comments

1
$('#mySelect').change(function(){
    $(#mySelect option).each(function(index){
        if ($(this).attr('selected') {
            console.log(index);
        }
    });
})

You may have to change out .attr() for .prop() depending on your version of Query

May also use

$('#mySelect').change(function(){
    $("#mySelect option").index($("#mySelect option:selected"))
})

2 Comments

Why not use $("#mySelect option:selected") instead of a loop?
instead of .each you can directly use $('option:selected' , this).index()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.