Reputation: 43
I'm using jQuery UI's autocomplete to try to propagate the correct input for a form, with over 1000 vaules.
The autocomplete works fine, but how do I restrict the value of the field to just those values?
Autocomplete code in the form:
$('#animal').autocomplete({
source: "search_species.php",
minLength: 3,
select: function(event, ui) {
$('#animal').val(ui.item.postcodes);
$('#code').val(ui.item.code);
$('#family').val(ui.item.family);
}
});
Code in autocomplete source:
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$return_arr = array();
if ($conn){
$fetch = mysql_query(
"SELECT * FROM animals where animals like '%" . mysql_real_escape_string($_GET['term']) . "%'"
);
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['value'] = $row['animals'];
$row_array['family'] = $row['family'];
$row_array['code'] = $row['code'];
array_push($return_arr,$row_array);
}
}
mysql_close($conn);
echo json_encode($return_arr);
As I said, the autocomplete works. I just need to know how to limit the values in the text field to those in the search so that people can't type in their own values.
Upvotes: 3
Views: 3109
Reputation: 21737
There are a few ways you can go about this.
One way is to clear the input value if nothing from the dropdown was selected, and force the field to be non-empty when it's submitted. A good way to clear the value is to use the autocomplete event for when the menu changes or closes, which is named change. This event fires if either an item is selected, or the input loses focus. If the user did not select an item from the menu, then the ui.item
value will be null and you can clear the typed value left in the input.
You could implement the method like this:
$('#animal').autocomplete(
{
source: "search_species.php",
minLength: 3,
select: function(event, ui) {
$('#animal').val(ui.item.postcodes);
$('#code').val(ui.item.code);
$('#family').val(ui.item.family);
},
change: function(event, ui) {
if(ui.item === null || !ui.item)
$(this).val(''); /* clear the value */
}
});
From here it's straightforward to add a check in your form validation, or whatever you're using, to prevent the user from moving on unless an item was chosen--by ensuring the input value is non-empty.
Upvotes: 2