views:

89

answers:

4

Hi,

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.

+1  A: 

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();
Corey
Thanks, but this syntax doesn't work.
Tom
+1  A: 

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

Adam Kiss
Yeah, wouldn't normally be needed, but it's a repopulation of $_POST select options (when form submission failed validation) for dynamic selects that were populated with Ajax on first load, so the page can't remember them. The countrycode I pass to JQuery via PHP.
Tom
well its either something like `$('select[value=*]')` -> tag[value] OR `$(#id)` -> id :] - it does not make sense at all to use both, needless to say in this combination.
Adam Kiss
Thanks for your comments, but I think you've misunderstood the question. Imagine #Dropdown as a unique select on the page.
Tom
+5  A: 

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

var countrycode = '55';
var name = $("#Dropdown option[value="+countrycode+"]").text();
munch
This works.... thanks very much. Resolved.
Tom
+1  A: 

try:

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