Reputation: 2299
I have an autocomplete form box which displays a label, and then inserts a value once selected. I would like to use part of the label (client_id) to form part of the form post once it is submitted.
JS:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php',
minLength: 2,
select: function (event, ui) {
return showUser(ui.item.value)
},
change: function (event, ui) {
return showUser(ui.item.value);
},
});
});
</script>
backend_search_addressWT.php
<?php
require_once 'config.php';
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $mysqli->query("SELECT * FROM client WHERE client_address LIKE '%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = array (
'label' => $row['client_address'].' - '.$row['client_name'].' - '.$row['client_id'],
'value' => $row['client_address'],
'value2' => $row['client_id'],
);
}
//return json data
echo json_encode($data);
?>
I have tried adding this to the js, to no avail:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php',
minLength: 2,
select: function (event, ui) {
return showUser(ui.item.value);
var label = (ui.item.label).split('-')
var client_id = label[2]
$('#hiddenID').client_id
},
change: function (event, ui) {
return showUser(ui.item.value);
},
});
});
</script>
Notice that I already use a select callback on the value ui.
How can I access the label?
Upvotes: 0
Views: 263
Reputation: 28196
In your select()
method you added code after the return
statement:
select: function (event, ui) {
return showUser(ui.item.value);
var label = (ui.item.label).split('-')
var client_id = label[2]
$('#hiddenID').client_id
}
These lines will never be executed.
What do you expect $('#hiddenID').client_id
to do for you? This will most likely achieve nothing, since it looks for a (probably not existing) property of a jquery element which it then discards again.
Instead (edited):
Place the label processing instructions before the return statement and see what happens. Maybe start by showing the label in the console first and then putting it into a hidden input field:
select: function (event, ui) {
console.log(ui.item.label); // just to make sure there is something to process ...
$('#hiddenID').val(ui.item.label.split(' - ').pop()); // to place the last portion
// of the label in that hidden element (assuming it is an input field)
return showUser(ui.item.value);
}
The .split(' - ').pop()
will return only the last element of the label string (assuming the components are separated by a ' - '
string).
Upvotes: 1