Tom
Tom

Reputation: 30698

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.

Upvotes: 1

Views: 1044

Answers (4)

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

try:

var name = $("#Dropdown option[value=" + countrycode + "]").text()

Upvotes: 1

munch
munch

Reputation: 6321

You need to look for the option value within the select.

var countrycode = '55';
var name = $("#Dropdown option[value="+countrycode+"]").text();

Upvotes: 5

Adam Kiss
Adam Kiss

Reputation: 11859

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=*].

Upvotes: 1

Corey
Corey

Reputation: 1542

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();

Upvotes: 2

Related Questions