我正在尝试使用动态文本字段生成的jquery自动完成,自动完成工作,但主要问题是我无法正确填充名称为'alamat'的文本字段。如何在自动完成中正确设置当前文本字段'alamat'值?
HTML
<form id="myForm" name="myForm" method="post">
<table id="myTable" border="1" cellpadding="1" cellspacing="1">
<thead>
<th>No</th><th>Nama</th><th>Alamat</th>
</thead>
<tbody></tbody>
</table>
<input id="addButton" name="addButton" type="button" value="Add an input" />
<input id="removeButton" name="removeButton" type="button" value="Remove an input" />
</form>
JS
<script type="text/javascript">
var counter = 1;
$(function() {
var options = {
source: 'autocomplete.php',
minLength: 2,
focus: function( event, ui ) {
$( '#nama_' + counter ).val( ui.item.value );
$( '#alamat_' + counter ).val( ui.item.alamat );
console.log(ui.item.alamat);
},
select: function( event, ui ) {
$( '#nama_' + counter ).val( ui.item.value );
$( '#alamat_' + counter ).val( ui.item.alamat );
console.log(ui.item.alamat);
}
};
$('input.searchNama').live("keydown.autocomplete", function() {
$(this).autocomplete(options);
});
var addInput = function() {
if (counter > 1){
$('input#removeButton').removeAttr('disabled');
}
var inputHTML = ' <tr><td><div id="' + counter + '">'+ counter +'</div></td><td><input type="text" id="nama_' +counter + '" class="searchNama" name="nama_' + counter +' " value="" /></td><td><input type="text" id="alamat_' + counter + '" class="searchAlamat" name="alamat_' + counter + '" value="" /></td></tr>';
$(inputHTML).appendTo("table#myTable tbody");
$("input.searchNama:last").focus();
counter++;
};
var removeInput = function() {
counter--;
if(counter == 1){
$('input#removeButton').attr('disabled','disabled');
counter++;
console.log('Jika Counter == 1 :' + counter);
} else {
$("table#myTable tbody tr:last").remove();
console.log('Jika Counter != 1 :' + counter);
}
};
if (!$("table#myTable tbody").find("input.searchNama").length) {
addInput();
}
$("input#addButton").click(addInput);
$("input#removeButton").click(removeInput);
});
</script>
我的autocomplete.php生成JSON结果
[{
"label": "Aditya Nursyahbani - Jl. Bratasena IX Blok U6 No. 7",
"value": "Aditya Nursyahbani",
"alamat": "Jl. Bratasena IX Blok U6 No. 7"
},
{
"label": "Slamet Aji Pamungkas - Jl. Melati 2 No. 3",
"value": "Slamet Aji Pamungkas",
"alamat": "Jl. Melati 2 No. 3"
}]
我在这个link中上传了我的脚本!
先谢谢。
答案 0 :(得分:0)
$('input.searchAlamat').val(ui.item.alamat);
您的选择器将填充页面中包含class='searchAlamat'
的所有输入。
在select
回调中,this
将是自动完成绑定的当前输入实例,因此您可以遍历它所在的行:
$(this).closest('tr').find('input.searchAlamat').val(ui.item.alamat);
的 DEMO 强>
请注意,我删除了focus
功能