jQuery autocomplete working : Need to get the row ID into hidden form field

I have the official qQuery autocomplete plugin ( from bassistance) working properly. Start typing a product name and it queries my php script and mysql to return a list of products.

However, when the user submits the form, I want a hidden form field that contains the row ID for that product in the database table. I would have thought that this is a very common need, but I did not see any of the examples in the doc or website.

Desired query:

SELECT sensor, sensorID FROM sensorTable WHERE sensor LIKE '\\\\$q%' " 

Desired form for submission

<form....>
<input type="text" id="sensor" />
<input type="submit" name="retrieveSensor" value="Get Sensor" />
<input type="hidden" name="rowID" value="...returned from ajax call..." />
</form>
$("#sensor").autocomplete("autocomplete.php", {
		width: 155,
		selectFirst: false,
		autoFill: true,
		mustMatch:true,
		max: 120

	});

This looks like the appropriate part of the api
http://docs.jquery.com/Plugins/Autocomplete/result#handler

You might need to take care that the value in your hidden field is always related to the value visible to the user, since they can probably change it. Maybe store two hidden fields, so that you can compare them serverside to make sure they match.

Thanks - that steered me to the solution although it took some trial and error.


$("#sensor").autocomplete("autocomplete.php", {
	width: 155,
	selectFirst: false,		
	autoFill: true,  			
	mustMatch:true,  	
	max: 120,  				
	formatItem: function(data, i, n, value) {
		return  value.split("|")[0];
	}
});
		
$("#sensor").result(function(event, data, formatted) {
	var hidden = $("#rowID");
	hidden.val( (hidden.val() ? hidden.val() + ";" : hidden.val()) + data[1]);
});

 });

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" id="sensor" name="sensor" />
<input type="hidden" id="rowID" name="sensorID" value="" />
<input type="submit" name="retrieveSensor" value="Get Sensor" />
 </form>

$query = "SELECT sensor, sensorID FROM ListSensor WHERE sensor LIKE '\\\\$q%' ";
$rs = query($query);
if (mysql_num_rows($rs) > 0) {
	while($row = mysql_fetch_array( $rs )) {
		echo $row['sensor'].'|'.$row['sensorID']."\
";
	} 	
}