Jquery autocomplete displaying more detail in drop down - php

I have a autocomplete function that works fine but where I want to extend the drop down details a bit. It looks like this:
Datafile (form-lookup.php):
if ($db)
{
$fetch = mysqli_query($db,"SELECT * FROM uni_labels where label_name like '%" . $_GET['term'] . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['label'] = htmlspecialchars_decode($row['label_name']);
$row_array['lookupid'] = $row['id'];
$row_array['address'] = $row['label_address'];
$row_array['number'] = $row['label_number'];
$row_array['postalcode'] = $row['label_postalCode'];
$row_array['country'] = $row['label_country'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysqli_close($db);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
My page that retreives the data looks like this:
$(function() {
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui)
{
$('#step1Name').val(ui.item.address);
$('#lookupid').val(ui.item.lookupid);
$('#vej').val(ui.item.address);
}
});
});
<input maxlength="100" type="text" required="required" class="form-control input-lg" name="step1Name" id="step1Name" />
Everyting works just great, but I would like for my drop down to show both $row_array['label'] and $row_array['address'], and when I select a value in the drop down, the input box will only output the $row_array['label'] value.
In the datafile I have tried to add the address to the label, like this:
$row_array['label'] = htmlspecialchars_decode($row['label_name'])." - ".$row['label_address'];
This displays the value fine in the drop down, but when selecting the choice, the input box of course contains too much data, where I only want it to display the label_name.
Can someone point me in the right direction?
Thanks in advance.

Add this to your autocomplete code:
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
},
focus: function(event, ui) {
return false;
}
So your updated autocomplete code will be like that:
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
return false;
},
focus: function(event, ui) {
return false;
}
});

Related

How can I add link to json_encode?

How can I add clickable link to json_encode?
I did a multiple query auto complete textbox with jquery. Maybe that's not the correct way how to do multiple queries but that's works anyway.
$conn = new PDO("mysql:host=".DB_SERVER.";port=3306;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM azonositok WHERE guid LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['guid']; /// I want to link to http://example.com/guid.php
}
$stmt1 = $conn->prepare('SELECT * FROM felhasznalok WHERE fnev LIKE :term');
$stmt1->execute(array('term' => '%'.$_GET['term'].'%'));
while($row1 = $stmt1->fetch()) {
$return_arr[] = $row1['fnev']; /// I want to link to http://example.com/profile.php
}
} catch(PDOException $e) {
echo 'HIBA: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
You'll have to add a function to execute on selection of an item in the autocomplete widget's dropdown list.
This is done with the select property as follows:
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
select: function(event, ui) {
window.location.href = ui.item.value;
}
});
This changes the current window's location to the selected item's value.
EDIT:
To change the default behavior where the value is displayed on focus/select to display the label instead, you could try:
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$('.auto').val(ui.item.label);
window.location.href = ui.item.value;
},
focus: function(event, ui) {
event.preventDefault();
$('.auto').val(ui.item.label);
}
});

jQuery Autocomplete ignore 0

Users enter values like 01234 and 12345. I would like to ignore the 0 when a users enters.
<input name="location" class="input-lg" style="width:100%;" id="location" type="text" size="50" placeholder="<?php echo $this->lang->line('inputhint');?>" />
$(function() {
var availableLocations =
<?php
// print the json array containing all zips
echo $locations;
?>
$("#location").autocomplete({
source: availableLocations,
minLength: 3,
focus: function (event, ui){
$('#location').val(ui.item.value);
return false;
},
select: function (event, ui){
$('#location').val(ui.item.value); // display the selected text
$('#locationid').val(ui.item.key); // save selected id to hidden input
return false;
},
change: function (event, ui){
// write value to hidden field
$( "#locationid" ).val( ui.item? ui.item.key : 0 );
return false;
}
});
});
Is there any way to do that? I tried a lot of things, but I can not handle it. Any idea?
The following is untested, but it works something like this:
$("#location").autocomplete({
source: function(request, response) {
// manipulate your search term
var yourTerm = parseInt(request.term);
// run a filter function on your data...
var filteredArray = $.map(availableLocations, function(item) {
// or whatever your matching rule is....
if( item.startsWith(yourTerm)){
return item;
} else{
return null;
}
});
// return the filtered values
response(filteredArray);
}
});

jquery Auto complete response coming as array how can i call two fields like name and photo

This is the form field with input type text.
<span>
<img src="images/author2.jpg" width="50" /> //in Database i have profilepic/userimage.jpg and the image shown in above is a static image.
<input class="searchStudent" type="text" autocomplete="off">
</span>
I have entered letter "A" and the response is coming as a array.i want to show the photo and names of the user how can i do that...?
This is my from script to get the details:
/*Search Student starts here*/
$(document).on("focus keyup", "input.searchStudent", function (event) {
$(this).autocomplete({
source: 'gdcontroller.php?action=search',
select: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
},
focus: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
});
/*Search Student ends here*/
This is my controller, here I am searching available students with name "A"
and fetching their details:
if($_GET['action']=="search" && $_GET['term']!='')
{
$keysearch = $_GET['term'];
$studentValue = trim($_GET['studentname']);
$studentsQuery =$conn->query('select s.student_pid,i.email,s.student_email,s.student_fname,s.student_lname,s.profile_pic from r_job_invitations i
LEFT JOIN tbl_students s ON i.email = s.student_email where i.id_job =54 and accounttype = 1 and inv_res = 1 and student_fname LIKE "'.$keysearch.'%" OR student_lname LIKE "'.$keysearch.'%" ')or die(mysqli_error());
$studentData = array();
while($student = $studentsQuery->fetch_assoc()){
$studentData[]= $student;
}
echo json_encode($studentData);
exit;
}
<div id="photoContainer"></div>
$(document).on("focus keyup", "input.searchStudent", function(event) {
$(this).autocomplete({
source: 'gdcontroller.php?action=search',
select: function (event, ui) {
event.preventDefault();
//I'm having trouble here; even name is not coming:
student.student_fname.value = ui.item.student.student_fname;
$("#photoContainer").append('<img src="' + ui.item.student.profile_pic + '">');
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
});

Separate json encoded array result

The following php block searches and returns names and i want to select an item and at ajax be able to get other items in the row selected beside "name". How do i separate them with ajax?
<?php
require_once '../php/db_conx.php';
$req = "SELECT name "
."FROM profiles "
."WHERE name LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
Here's ajax.
$(function() {
$( "#SearchInput").autocomplete({
source: 'Search.php',
minLength: 1,
select: function(event, ui) {
$('#Name').append(ui.item.label);
}
});
});
You can use _renderItem method
_renderItem: function( ul, item ) {
$( "#selector" ).text( item.name );// let name is in json
}
Or you can get the name in select event also like,
select: function(event, ui) {
$('#Name').append(ui.item.label);
$( "#selector" ).text( item.name );// let name is in json
}
Try this:
I think you need to parse data from array.
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
Use the variable name you have used.
Read More on: http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx
Thanks

getting jquery autocomplete to pass item to another field when selected

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

Categories