Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery autocomplete showing id and not label

I'm using jquery's autocomplete function and it's working just fine except that when I select something from the drop down list, the input field get populated with the value and not the label.

My code is as follows:

 <?php
   $query =     mysql_query("SELECT users.* FROM users JOIN peers ON peers.peer = users.user_id WHERE peers.user_id = '".$_SESSION['id']."'")or  die(mysql_error());
   $count   =   mysql_num_rows($query);
   $i   =   0;

   while($row = mysql_fetch_assoc($query))
   {
       $first[$i]   =   $row['first_name'];
       $last[$i]    =   $row['last_name'];
       $user_id[$i] = $row['user_id'];

       $i++;
   }

$data = "";

for($i=0;$i<$count;$i++)
{
    if($i != ($count-1))
    {
        $data .= '{ value: '.$user_id[$i].', label: "'.$first[$i].' '.$last[$i].'" }, ';
    } else
    {
        $data .= '{ value: '.$user_id[$i].', label: "'.$first[$i].' '.$last[$i].'" }';
    }
}
?>
<script type="text/javascript">
$("#auto").autocomplete({ 
    source: data,
    select: function(event, ui)
    {
        var id = ui.item.value;
        var name = ui.item.label;
    }
  });
  </script>

  <input type="text" value="Enter a connection's name" id="auto" />
like image 582
Lance Avatar asked May 02 '12 01:05

Lance


1 Answers

The default behavior of the select event is to update the input with ui.item.value. This code runs after your event handler.

Simply return false or call event.preventDefault() to prevent this from occurring. Try this,

<script type="text/javascript">
    $("#auto").autocomplete({ 
        source: data,
        select: function(event, ui)
        {
           var id = ui.item.value;
           var name = ui.item.label;
           $("#auto").val(name);
           return false;
        },
        focus: function(event, ui){
          return false;
        }
   });
</script>
like image 158
kd12 Avatar answered Oct 17 '22 17:10

kd12