Rocco The Taco
Rocco The Taco

Reputation: 3777

PHP/MySQL while loop not parsing

I have the following code that I modified to do a join and then build an array for a later form element:

$usersitems = '';
$db_connection = mysql_connect($dbhost,$dbuser,$dbpassword);
if($db_connection && mysql_select_db($dbname,$db_connection)){
    $usersquery = 'SELECT DISTINCT tablea.uid, tableb.FirstName, tableb.LastName FROM tablea, tableb WHERE tablea.uid = tableb.EmpNo ORDER BY tablea.uid ASC';
    $users = mysql_query($usersquery,$db_connection);
    if($users){
        while ($user = mysql_fetch_array($users, MYSQL_NUM)) {
            $usersitems .= '<option value="'.$user[0].'">'.$user[0].'- '.$user[1].' '.$user[2].'</option>';  
        }
        mysql_free_result($users);
    }
    mysql_close($db_connection);
} 

I also updated the options to include [1] and [2] to display FirstName and Lastname for each option from the original:

<option>'.$user[0].'</option>

This successfully creates this:

<select id="user_id"><option value="104">104- John Doe</option>

In my javascript I found this line of text I believe used to consume the selected in the form:

uid = $("#user_id option:selected").text();

Now suddenly this is not working? I'm assuming this is because the original '.$user[0].' was not looking for the value="'.$user[0].'" inside the option. How do I modify this?

Upvotes: 0

Views: 57

Answers (1)

Barmar
Barmar

Reputation: 781004

Change your code to:

uid = $("#user_id").val();

This returns the value of the selected option.

This will also work with the old way you were doing the options. If an option doesn't have a value attribute, the text is used by default.

Upvotes: 3

Related Questions