Reputation: 301
How can I find the index of a dropdown for a given value using jQuery?
Here is my dropdown with three values:
I'm able to get the index of the selected value like below
var index = $("#mydropdown").find("option:selected").val();
But I need to know the index of manager by passing manager as an argument to a jQuery function to get the index
I tried like this but it's not working
var index = $("#mydropdown").find("manager").val();
Upvotes: 2
Views: 533
Reputation: 367
Note: If you need to force the user to make a selection use an empty option and then have code check for a value ='0' or an index of zero respectively. I have added an empty option in both implementations below for this purpose.
Implementation #1:
function optionchanged()
{
var i = $("#option1").val();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
}
Assign index to value property in each option allows you greater control over the value returned.
<select id="option1" onchange="optionchanged();">
<option value="0"></option>
<option value="1">Admin</option>
<option value="2">Manager</option>
<option value="3">Employee</option>
</select>
The Console Output looks like this:
Selecting 'Admin' produces:
The Index of option selected is: 1
The Text of option selected is: Admin
Selecting 'Employee' produces:
The Index of option selected is: 3
The Text of option selected is: Employee
Implementation #2:
If you don't want to add the index to value you can reference the index directly in jQuery like this:
function optionchanged()
{
//var i = $("#option1 ").val();
var i = $("#option1 option:selected").index();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
//alert("Value of option 1 is: " + index);
}
<select id="option1" onchange="optionchanged();">
<option></option>
<option>Admin</option>
<option>Manager</option>
<option>Employee</option>
</select>
The console output will look the same as above.
Upvotes: 0
Reputation: 33870
You can either use :contains
or .filter()
. I personally prefer .filter()
:
var index = $("#mydropdown").find(":contains(manager)").val();
//Or
var index = $("#mydropdown").filter(function(){
return $.trim($(this).text()) === "manager";
}).val();
This assume your drop down look like this :
<select>
<option value="1">admin</option>
<option value="2">manager</option>
<option value="3">employee</option>
</select>
Upvotes: 3