我尝试了typeahead updater来进一步处理数据。在这里,我使用我的代码。看看并帮助我。
我的HTML:
<input type="text" class="form-control" data-provide="typeahead" name="pname" id="pname" autocomplete="off">
<table id="pytable"> <tbody></tbody>
</table>
我的JSON:
[{"pname":"iPhone4","id":"14","pid":"PRO14"},{"pname":"iphone5s","id":"16","pid":"PRO16"}]
JS:
$('#pname').typeahead({
source: function (query, process) {
names = [];
map = {};
return $.get('/'+url_root_path+'/misc/purchase/source.php', { query: query }, function (data) {
//console.log(data);
var json_obj = $.parseJSON(data);
$.each(json_obj, function (i, obj) {
map = obj;
if($.inArray(obj.pname, names)==-1)
names.push(obj.pname);
// console.log(map);
});
return process(names);
});
}, // source
updater: function(item) {
//console.log(map);
//console.log(item);
//console.log(map.id);
var item_code = map.pid; var item_cost = 0;
var item_name = item;
var item_id = map.id;
var newTr = $('<tr id="row_'+ count +'"></tr>');
newTr.html('<td><input name="product'+ count +'" type="hidden" value="'+ item_code +'"><input class="span5 tran" style="text-align:left;" name="item'+ count +'" type="text" value="'+ item_name +' ('+ item_code +')"></td><td><input class="span2 tran" name="quantity'+ count +'" type="text" value="1" onClick="this.select();"></td><td><input class="span2 tran" style="text-align:right;" name="unit_cost'+ count +'" type="text" value="'+ item_cost +'"></td><td><i class="icon-trash tip del" id="'+ count +'" title="Remove this Item" style="cursor:pointer;" data-placement="right"></i></td>');
newTr.appendTo("#pytable");
} //updater
}); //typehead
我的问题是,当我点击更新程序时,它会为每个名称相似的产品添加相同的pid。
答案 0 :(得分:0)
您可以使用obj.name
使用obj
数组映射到map
对象:
JS:
$('#pname').typeahead({
source: function (query, process) {
names = [];
map = {};
return $.get('/'+url_root_path+'/misc/purchase/source.php', { query: query }, function (data) {
var json_obj = $.parseJSON(data);
$.each(json_obj, function (i, obj) {
map[obj.pname] = obj; //<------ make this change
if($.inArray(obj.pname, names)==-1)
names.push(obj.pname);
});
return process(names);
});
},
updater: function(item) {
//change the below line
var item_code = map[item]['pid'] , item_cost = 0, item_name = item , item_id = map[item]['id'];
var newTr = $('<tr id="row_'+ count +'"></tr>');
newTr.html('<td><input name="product'+ count +'" type="hidden" value="'+ item_code +'"><input class="span5 tran" style="text-align:left;" name="item'+ count +'" type="text" value="'+ item_name +' ('+ item_code +')"></td><td><input class="span2 tran" name="quantity'+ count +'" type="text" value="1" onClick="this.select();"></td><td><input class="span2 tran" style="text-align:right;" name="unit_cost'+ count +'" type="text" value="'+ item_cost +'"></td><td><i class="icon-trash tip del" id="'+ count +'" title="Remove this Item" style="cursor:pointer;" data-placement="right"></i></td>');
newTr.appendTo("#pytable");
}
});