1

I have been reviewing a lot of pages about this and can't seem to figure out why this isn't working.

In an HTML page I am using PHP to dynamically create a dropdown box on the page like this:

$sel = '<select "id"="userPhones">';

foreach ($user_phones as $single_phone) 
{
$phoneId = $single_phone['id'];
$phoneNum = $single_phone['phone_num'];
if($single_phone['isdefault']=='1')
{
    $sel.="<option id=".$phoneId." selected='selected'>".$phoneNum."</option>";
}
else
{
    $sel.="<option id=".$phoneId.">".$phoneNum."</option>";
}
}
$sel .='</select>';
echo $sel;

I see the dropdown appear on the page without a problem and it all looks like it is working. But then later I try to use JQuery to get at the value of the dropdown to act on it by doing this:

phone_num = $('#userPhones :selected').val();
alert(phone_num);

For some reason whenever I try to get at the value I am getting an alert of "undefined" and not the value of the dropdown. I am sure this is being set because I have looked at he source of the page and I have checked with Firebug that the elements exist on the page. I have tried just using the ID of the dropdown and val(), I have tried using text() but cannot seem to grab anything. Can someone please tell me what on earth is going on here? I have been racking my brains about this for a while now.

1
  • 1
    Why are you quoting 'id' in the statement: $sel = '<select "id"="userPhones">';? Incidentally, jQuery works client-side, so it's the rendered (x)html we'd need to see to help out properly. Commented Apr 29, 2011 at 16:54

1 Answer 1

3

The id field in the select element should not have quotes around it. It's not valid markup and so jQuery does not find it with that id.

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

1 Comment

That did it!! Thanks so much for putting an end to my torture!

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.