0

How can I get selected option index of <SELECT> with javascript. It is easy to get value with the help of jQuery's val() method but I couldnt get the index 0, 1, 2...

I can get it by some painful ways but I believe there must be something which can do it directly.

I create my select element on fly like this :

$formInput = $('<select class="userInput">');
$.each([A,B,C,D,E], function (i, v) {
    $option = $('<option value="' + v + '">' + v+ '</option>');
    $formInput.append($option);
});

And all methods I tried

$formInput.prop("selectedIndex")

$formInput.get(0).selectedIndex

$formInput[0].selectedIndex

did not work.

Here is the FIDDLE

2 Answers 2

1

use selectedIndex property of the DOM element:

$("#selectElement")[0].selectedIndex

using javascript

document.getElementById('selectElement').selectedIndex

Fiddle

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

4 Comments

Thank you but I guess I asked this question in wrong way. I edited my question. I created my select element on the fly and I think it changes something. Could you please check it again
try $(".userInput")[0].selectedIndex
There are a lot of these objects and I have to reach their selectedIndex.I prefer reaching them while generating instead of selecting them after generation.
would be great if you can create the fiddle
0

using index()

$("#selectElement option[selected]").index()

Comments

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.