Tutorial :getting jquery autocomplete to pass item to another field when selected



Question:

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 shutting down!!!!!!!!


Solution:1

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     }  });  

});


Solution:2

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     }  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »