Link to home
Start Free TrialLog in
Avatar of evibesmusic
evibesmusicFlag for United States of America

asked on

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

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

Avatar of evibesmusic
evibesmusic
Flag of United States of America image

ASKER

@All:

So here is a screen shot to help out with my description of the issue:
User generated image
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.
Avatar of James Rodgers
put the name in, insert the numeric code into a hidden text field, the name is user friendly, the numeric code is system friendly
could you open your page in your web browser :
http://yoursiteaddress/search.php?term=Brian

And post what you get here
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!
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.
SOLUTION
Avatar of Roopesh Reddy
Roopesh Reddy
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@roopeshreddy you still need to get the data to your receiver page which is the first 4 steps above.
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!
@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
}
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...
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

@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" />
<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
@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

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"]);      
            }
@Jester_48:

Alert says "[object Object]".
ok try
alert(cache.NUID);
@Jester_48:

Alert says "undefined".
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)
//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"]);      
                  }
      });
});
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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"]);      
 }
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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.
@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