I'm using Bootstrap-3-Typeahead here for my autocomplete from mysql. I need to get item_code from selected item_name afterSelect with something like
$('#item_code').val(this.item_code);
unfortunately not working.
My Json output:
[{"item_code":"1","item_name":"A"},{"item_code":"2","item_name":"B"}]
here's my code, please advise
$('input.item_name').typeahead({
minLength: 3,
source: function (query, process) {
$.ajax({
url: 'function/load-item.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
var newData = [];
$.each(data, function(){
newData.push(this.item_name);
});
return process(newData);
}
});
},
afterSelect: function(){
$('#item_code').val( ... ... ... ... );
}
});
My php code
<?php
session_start();
include ('../include/connect.php');
$query = 'SELECT item_code,item_name FROM master_item';
if(isset($_POST['query'])){
$query .= ' WHERE item_name LIKE "%'.$_POST['query'].'%"';
}
$return = array();
if($result = $conn->query($query)){
// fetch array
while ($row=mysqli_fetch_assoc($result))
{
$return[] = $row;
}
// free result set
$result->close();
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
}
?>
This is for the benefit of those who might have the same problem in the near future. Below is another simple approach to getting the same functionality using JQuery and bootstrap-3-typeahead.js or bootstrap-3-typeahead.min.js:
var url = "codePath/searchCode.php";
$('.typeahead').typeahead({
source: function (query, process) {
return $.get(url, { query: query }, function (data) {
console.log(data)
return process(data);
});
},
//this triggers after a value has been selected on the control
afterSelect: function (data) {
//print the id to developer tool's console
console.log(data.id);
}
});
Try Using typeahead:selected
instead of afterSelect
it returns the whole object where you can get your required value i.e. .item_code
. I have created this fiddle , you can see the working example there.
$('.typeahead').on('typeahead:selected', function (e, datum) {
console.log(datum);
$('#item_code').val(datum.item_code);
});
replying on old thread, your code seems to be good, you just missed the argument to the afterSelect callback
$('input.item_name').typeahead({
minLength: 3,
source: function (query, process) {
$.ajax({
url: 'function/load-item.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
var newData = [];
$.each(data, function(){
newData.push(this.item_name);
});
return process(newData);
}
});
},
afterSelect: function(args){
$('#item_code').val(args.item_code );
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With