vin*_*ter 6 twitter-bootstrap bootstrap-typeahead
我使用的是引导-3-事先键入的内容在这里为从MySQL我自动完成.我需要在选择之后从选定的item_name获取item_code
$('#item_code').val(this.item_code);
Run Code Online (Sandbox Code Playgroud)
不幸的是没有工作.
我的Json输出:
[{ "ITEM_CODE": "1", "ITEM_NAME": "A"},{ "ITEM_CODE": "2", "ITEM_NAME": "B"}]
这是我的代码,请指教
$('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( ... ... ... ... );
}
});
Run Code Online (Sandbox Code Playgroud)
我的PHP代码
<?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);
}
Run Code Online (Sandbox Code Playgroud)
?>
尝试使用typeahead:selected而不是afterSelect它返回整个对象,您可以获得所需的值,即 .item_code.我创造了这个小提琴,你可以在那里看到工作的例子.
$('.typeahead').on('typeahead:selected', function (e, datum) {
console.log(datum);
$('#item_code').val(datum.item_code);
});
Run Code Online (Sandbox Code Playgroud)
小智 5
这是为了在不久的将来可能遇到相同问题的人们的利益。 下面是使用JQuery和bootstrap-3-typeahead.js或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);
}
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9547 次 |
| 最近记录: |