JQuery: How to get name of a select when value is known?
I need to get the name of a select (#Dropdown) when its value is known but can't seem to get the syntax right. Here's an example:
$(document).ready(function()
{
var countrycode = '55';
var name = $("#Dropdown[value=countrycode]").text(); // fails here
if(name == 'Germany')
{..... etc
I can get it to work as follows in a different context when I'm 开发者_如何转开发able to use "this":
var name = $(this[value=countrycode]).text();
... but that's not available in the first example.
Anyone? Thanks.
You need to look for the option value within the select.
var countrycode = '55';
var name = $("#Dropdown option[value="+countrycode+"]").text();
You're including "countrycode" literally in your selector string.
There's probably a better way to do it, but this should work:
var name = $("#Dropdown[value=" + countrycode + "]").text();
Post also HTML, it seems kind of wrong - you can have just one ID (#something) per page, so there would be no need for something like #id[value=*]
.
try:
var name = $("#Dropdown option[value=" + countrycode + "]").text()
精彩评论