Solved

How to use jquery to autocomplete a text box with a value other than that which appears in the drop down box?

Posted on 2013-06-17
25
3,794 Views
1 Endorsement
Last Modified: 2013-06-19
Experts,

This question is a continuation of the following question: click here

I tried a workaround which has ultimately led me back to this question cause the workaround is more trouble than it is worth.

My PHP script connects to the database and pulls three pieces of information: FirstName, LastName, and UniqueID. The FirstName and LastName are shown to the user in the dropdown box.

My issue is this...

I'd like to insert the UniqueID into the text box when a name is selected rather than having it populate with the First and Last Name that was selected by the user.

Example:

1) User types in "Jo"
2) The dropdown menu reveals the first and last name "Bob Jones".
3) When the user selects the name "Bob Jones" from the drop down list, I'd like the form field to be filled with Bob Jones' UniqueID "xyz123" versus filling the field with the text "Bob Jones".

Can anyone help me figure out how to do this? My code is attached below.

jquery code:
<title>jQuery UI Autocomplete - Remote with caching</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
var cache = {};
$( "#names" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="names">Select Name: </label>
<input id="names" />
</div>
</body>
</html>

Open in new window


search.php:
<?php
include('../scripts/db_connection.php');
//connect to your database
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT FirstName, LastName, UniqueID FROM sandbox.members WHERE FirstName LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
	$row_set[] = $row['FirstName'].' '.$row['LastName'];//build an array
}
echo json_encode($row_set);//format the array into json data
?>

Open in new window

1
Comment
Question by:evibesmusic
  • 10
  • 7
  • 3
  • +4
25 Comments
 

Author Comment

by:evibesmusic
ID: 39254710
@All:

So here is a screen shot to help out with my description of the issue:
Current workflow
When a user types in a name, the suggestion box populates.

When the user selects the name, I want the field to populate with only the UniqueID.

In the case of Brian Jones, if his name is selected, I want only his UniqueID "H977241" to populate the box.
0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 39256014
put the name in, insert the numeric code into a hidden text field, the name is user friendly, the numeric code is system friendly
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39256018
could you open your page in your web browser :
http://yoursiteaddress/search.php?term=Brian

And post what you get here
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39256289
There are a lot of moving parts here.  The first thing I think I would do is to change line 10 of search.php to this:

$row_set[] = $row['FirstName'].' '.$row['LastName']. ' ' . $row['UniqueID'];

Once that change is made, you will be able to use JavaScript to access not only the names, but also the ID  that you need.

You might also want to adopt a coding standard for your JavaScript -- something that uses consistent indentation.  The computer doesn't care, but making the code easier for humans to read goes a long way toward making the code easier to debug!
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39256710
You already answered your question.  

"Found my own solution. Pass the full string of by submitting the form. Then use PHP to quickly and cleanly extract the part of the string that I need."

I use autocomplete all the time and this is exactly what I do.  

Step 1) User enters any combination of first & last & ID

Step 2) On receiver page, data comes in as a string "First Last 1234" or  "First 123" or "123" or  "Last"

Step 3) Receiver page breaks string into an array using the space as a delimiter.  Assume data starting with alpha is first or last name, assume data starting with numeric is the id.  Assume if two alpha variables, the first is the first name and the second is the the last name.  

Step 4) Pass the variables First, Last and ID separately in your SQL converting missing data as a wild card.

Step 5) Send back 2 fields of data as JSON.  DisplayName and ID.  Where DisplayName is "First Last 1234" and of course ID is "1234"

Step 6) In your jquery, parse the json to display the DisplayName back but place the selected ID in your hidden field.

This method may seem more complex then you want to tackle at first, but you break it down in parts, it will make sense.  It might be easier to break your question here into parts and tackle Steps 1,2,3 as one question, Steps 4, 5 as another and Step 6 as third.

The end result will be a cool factor from your user that they can enter in any or all of a first, last or id and come up with possible results.  The key is using the space in the input as a delimiter.
0
 
LVL 23

Assisted Solution

by:Roopesh Reddy
Roopesh Reddy earned 167 total points
ID: 39256913
Hi,

you are looking for Custom data display - http://jqueryui.com/autocomplete/#custom-data

Hope it helps u...
0
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39256974
@roopeshreddy you still need to get the data to your receiver page which is the first 4 steps above.
0
 
LVL 23

Expert Comment

by:Roopesh Reddy
ID: 39257005
Hi Padas,

As per the Author, he is getting the data, but he has an issue with splitting it and displaying what he wish to!
0
 

Author Comment

by:evibesmusic
ID: 39257012
@jester:

Can you show me how I'd insert the UniqueID into a hidden field given my current set up? This seems simple and logical to me and if it is easily implemented, that would be a plus.

@roopershreddy:

I like the idea of using the custom data display but, I struggle in that I don't know how I'd create the array in PHP?

The jquery array is passed in the following format (altered to meet my needs):

 var projects = [
{
value: "UniqueID",
label: "FristName LastName"
},
{
value: "UniqueID",
label: "FristName LastName"
},
{
value: "UniqueID",
label: "FristName LastName"
}
];

My lack of experience in creating custom PHP arrays makes me wonder if this format could be achieved?

How can I create an array where I can assign dynamic values to the variables "value:" and "label:"?

This is my current script in my search.php page:

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
      $row_set[] = $row['FirstName'].' '.$row['LastName'];//build an array
}
0
 
LVL 23

Expert Comment

by:Roopesh Reddy
ID: 39257106
Unfortunately, i don't know PHP!

I think it's not Array, it's JSON format!

json_encode should help you in coverting the PHP array to JSON - http://www.php.net/manual/en/function.json-encode.php

Hope it helps u...
0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 39257108
My set up is slightly different than yours
but add the select action to your definition

give this a shot


$( "#names" ).autocomplete({
	minLength: 2,
	source: function( request, response ) {
		var term = request.term;
		if ( term in cache ) {
			response( cache[ term ] );
		return;
		}
		$.getJSON( "search.php", request, function( data, status, xhr ) {
			cache[ term ] = data;
			response( data );
		});
	},
	select: function(event,ui){
		$('.hidden-input-class').val(cache[ 'UniqueID' ] );
				
	}

});

Open in new window

0
 

Author Comment

by:evibesmusic
ID: 39257121
@Jester_48:

Re: the following lines of code

      select: function(event,ui){
            $('.hidden-input-class').val(cache[ 'UniqueID' ] );
                        
      }

What would my input look like?

<input name="hidden-input-class" type="hidden" />
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 25

Expert Comment

by:James Rodgers
ID: 39257129
<input name="user_unique_id" class="hidden-input-class" type="hidden" value=""/>

but i would replace "hidden-input-class" with something more intuitive, and change the type to text while testing, update to hidden once debugging is complete
0
 

Author Comment

by:evibesmusic
ID: 39257611
@Jester_48:

OK...I think I am almost there. Still not getting the second text field to populate with the UniqueID.

A few notes: I used the words/term UniqueID in the example above. The actual item being pulled from my remote DB via the search.php script is call 'NUID'.

You will see my reference to NUID below where I thought it to be appropriate.

To recap, my search.php script is pulling the "FirstName", "LastName", and "NUID" from the database. The cached value that should be inserted into the 'nuid' text box is "NUID".

Can you help me get the rest of the way there. I don't see any change when the auto-complete suggestion is selected. It still only populates the auto-complete text box.

<title>jQuery UI Autocomplete - Remote with caching</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
	var cache = {};
		$("#names").autocomplete({
		minLength: 2,
		source: function(request,response){
			var term=request.term;
			if (term in cache) {
				response(cache[term]);
				return;
			}
			$.getJSON("search.php",request,function(data, status, xhr) {
				cache[term]=data;
				response(data);
				});
			},
		select:function(event,ui){
			$("#nuid").val(cache["NUID"]);	
		}
	});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="names">Select Name: </label>
<input id="names" />
</div>
<div class="ui-widget">
<label for="nuid">NUID: </label>
<input id="nuid" class="nuid" name="nuid" type="text" value="" /> 
</div>
</body>
</html>

Open in new window

0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 39257628
put an alert in the select: function make sure it is being activated/called

select:function(event,ui){
alert([cache]); // should show all items in cache var
                  $("#nuid").val(cache["NUID"]);      
            }
0
 

Author Comment

by:evibesmusic
ID: 39257710
@Jester_48:

Alert says "[object Object]".
0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 39257743
ok try
alert(cache.NUID);
0
 

Author Comment

by:evibesmusic
ID: 39257763
@Jester_48:

Alert says "undefined".
0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 39257787
then the NUID value is not part of the object and you cant access it

what is contained in the data variable passed?
alert(data)
0
 

Author Comment

by:evibesmusic
ID: 39257833
//ALERT SHOWS NOTHING WHEN I DO THIS
select:function(event,ui){
alert(data);
$("#nuid").val(cache["NUID"]);      
}

//ALERT FUNCTION SHOWS ALL OF THE AUTOCOMPLETE DATA WHEN I DO THE FOLLOWING
//SEEMS TO ME THAT THE DATA IS NOT MAKING IT TO THE SELECT FUNCTION
$(function() {
      var cache = {};
            $("#names").autocomplete({
            minLength: 2,
            source: function(request,response){
                  var term=request.term;
                  if (term in cache) {
                        response(cache[term]);
                        return;
                  }
                  $.getJSON("search.php",request,function(data, status, xhr) {
                        cache[term]=data;
                        response(data);
                        alert(data); // should show all items in cache var
                        });
                  },
                  select:function(event,ui){
                  $("#nuid").val(cache["NUID"]);      
                  }
      });
});
0
 
LVL 25

Assisted Solution

by:James Rodgers
James Rodgers earned 166 total points
ID: 39257840
damn, my fault, left my var in the call
change ui to cache (might need to be data)
 select:function(event,cache){
                  $("#nuid").val(cache["NUID"]);      
                  }
0
 

Author Comment

by:evibesmusic
ID: 39257880
@Jester_48:

Both of these variations produce the same message in the alert box "undefined".

select:function(event,data){
alert(data["NUID"]);
 $("#nuid").val(data["NUID"]);      
 }

select:function(event,cache){
alert(cache["NUID"]);
 $("#nuid").val(cache["NUID"]);      
 }
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 167 total points
ID: 39259973
greetings   evibesmusic, you seem to have a good handle on the javascript-jquery part of this code work, however, from the PHP code you have so far, as far as I can tell, it will never do anything like what you want to do because you do NOT ever pass down the uniqueID from the ROW in the database., You need to have the
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
    $row_set[] = array("label"=>$row['FirstName'].' '.$row['LastName'], "NUID"=>$row['UniqueID']);
}

echo json_encode($row_set);

Open in new window


this will send back to the javascript DECODED to an Object inside of a javascritp array if you want the Name as "value" you access from the getJSON data like it like -
data[0].value

unique ID as -
data[0].NUID

I am not sure about how the "cache" is read in the responce(), so you may need to reformat the PHP data send OR the way the data is read, I really can not tell for sure BUT you never seem to have any need for MULTIPLE row reads from the database, you might consider this for PHP -
$row = mysql_fetch_array($result,MYSQL_ASSOC);
 $row_set = array("label"=>$row['FirstName'].' '.$row['LastName'], "NUID"=>$row['UniqueID']);

echo json_encode($row_set);

Open in new window

you access THIS ONE from the getJSON data like it like -
data.value

unique ID as -
data.NUID

but like I said, it will depend on HOW and WHAT is read and or used  for the  response( data ), I do not have time to look it up now, sorry.
AND since you are using javascript, you can store the uniqueID in the javascript (perhaps it already is in cache) and you do not need a hidden input, just read the cache.NUID into the list value.
0
 

Author Closing Comment

by:evibesmusic
ID: 39260454
@All Experts:

Thank you very much for your help in answering this question.  The final code that I posted is a conglomeration of all of your ideas and is a hybrid of sorts.

Thank you for your help.
0
 

Author Comment

by:evibesmusic
ID: 39260510
@ALL - HERE IS THE FINAL CODE.

The code is a hybrid of the following two codes:

1) jquery autocomplete w/ Remote datasource
and
2) jquery autocomplete w/ Custom data and display

The code blends the two functions into one. It does the following:

1) Accepts user input
2) Retrieves data from the remote DB based on the user's input using PHP (search.php)
3) Uses these search results to populate the autocomplete box using JSON
4) When a user clicks on an item in the drop down list the following happens:
     4a) The first form field is populated with the First and Last name chosen.
     4b) A hidden field is populated with the data called "NUID"
     4c) The description is shown to the user.

Thanks to all those that helped solve this issue. Enjoy!

Here's the jquery/html (test.php):

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Custom data and display</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
</style>
<script>
$(function() {
	var projects = {};
	$( "#project" ).autocomplete({
		minLength: 2,
		source: function( request, response ) {
			var term = request.term;
			if (term in projects) {
				response(projects[ term ] );
				return;
			}
			$.getJSON("search.php",request,function(data,status,xhr) {
				projects[term] = data;
				response(data);
			});
		},
		focus: function( event, ui ) {
			$( "#project" ).val( ui.item.label );
			return false;
		},
		select: function( event, ui ) {
			$( "#project" ).val( ui.item.label );
			$( "#project-id" ).val( ui.item.value );
			$( "#project-description" ).html( ui.item.desc );
			return false;
		}
	})
	.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
		return $( "<li>" )
		.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
		.appendTo( ul );
	};
});
</script>
</head>
<body>
<?php
echo $_POST['project-id'];
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="test_variable_form" target="_self">
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project" />
<p id="project-description"></p>
<input name="project-id" type="hidden" id="project-id" value="" />
<input name="go" type="submit" value="go">
</form>
</body>
</html>

Open in new window


Here's the search.php file which provides the data:

<?php
include('../scripts/db_connection.php');
//connect to your database
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT FirstName, LastName, NUID FROM sandbox.members WHERE FirstName LIKE '%".$term."%' OR LastName LIKE '%".$term."%'";
$result = mysql_query($qstring) or die ("Could not run query: " . $qstring . "<br />\n" . mysql_error () );//query the database for entries containing the term

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
    $row_set[] = array("label"=>$row['FirstName'].' '.$row['LastName'], "value"=>$row['NUID'], "desc"=>$row['NUID']);
}

echo json_encode($row_set);
?>

Open in new window

0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now