开发者

getting jquery autocomplete to pass item to another field when selected

开发者 https://www.devze.com 2023-01-10 16:40 出处:网络
I\'ve been working on this for a couple of hours and it should work but i\'m missing something! basically, i\'m using jquery autocomplete with json source, with 2 values id and description.

I've been working on this for a couple of hours and it should work but i'm missing something!

basically, i'm using jquery autocomplete with json source, with 2 values id and description. Description should show up in suggestions and if item is selected and ID passed to a hidden field ( the field is not hidden currently for testing purposes)

here's my code:

$(function() {
  $("#CurrentProv").autocomplete({
   source: "inc/provider_term.php",
   minLength: 3,
    formatItem: function(data, i, n, value) {   
        return  value.split("|")[1];
          } 
    });
      $("#CurrentProv").result(function(event, data, formatted) {
      if (data)
            $("input#fid").val(data[0]);
      });
});

//PHP valid json output

$term = $_GET['term'];

$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());

while ($row = mysql_fetch_array($res)) {

$searchArray['value'] = $row['PID'].'|'.$row['PName'];
$search[] = $searchArray;

}

echo json_encode($search);

I've searched and done various variations and still doesn't work!!! My brain is shuttin开发者_如何学运维g down!!!!!!!!


First, switch to using the actual jQuery UI autocomplete.

You'll have to sort out how to format your items on the server side, or in your JSON callback, because formatItems is not supported anymore. Check out this guide for some help.

Now that you've done that, here's how it will look:

$(function() {
 $("#CurrentProv").autocomplete({
   source: "inc/provider_term.php", //or you can use a callback here
   minLength: 3,
   change: function(event, ui) {
      $("input#fid").val(ui.item.value);//or ui.item.desc perhaps
   }
});

});


Working tweaked PHP code and JS as Ryley suggested:

$term = $_GET['term'];

$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());

while ($row = mysql_fetch_array($res)) {

$searchArray['value'] = $row['PID'];
$searchArray['id'] = $row['PName'];
$search[] = $searchArray;

}

echo json_encode($search);


$(function() {
 $("#CurrentProv").autocomplete({
   source: "inc/provider_term.php", //or you can use a callback here
   minLength: 3,
   change: function(event, ui) {
      $("input#fid").val(ui.item.id);//or ui.item.desc perhaps
   }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消