【发布时间】:2018-08-30 04:19:04
【问题描述】:
我有 javascript,包括一个 ajax 调用,它采用空表单输入并使用用户键入的内容来查询 json 对象。它成功返回匹配的对象并将它们显示在数据列表中。
这一切都很好,但现在我试图确保当他们点击一个列表选项时,我只从那个选定的选项中获取某些字段,以便我最终可以将它们发布到一个表单中。
当单击一个选项时,我在控制台 (console.log(searchResult[i]._source.frm.grp.Name)) 中获得了我想要的值,但它为我提供了以前对象中的每一个,我只想要来自单击的对象的数据。
我认为这可能与我在 for 循环中执行该函数的事实有关,或者它与我使用 [i] 的索引有关,但我无法确定它。
我怎样才能让它只影响被点击的索引对象的值?
<script type="text/javascript">
//input event handler
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function(response){
$('#returnedProducts').empty();
let searchResult = response.hits.hits;
for(let i = 0; i < searchResult.length; i++) {
$("#returnedProducts").append("<option value=" + searchResult[i]._source.category + ">" + searchResult[i]._source.category + "</option>");
//Issue starts here//
$("#productInput").on('input', function(){
var val = this.val = this.value;
if($('#returnedProducts option').filter(function(){
return this.value === val;
}).length){
document.getElementById("grpName").value = searchResult[i]._source.frm.grp.grp_name;
document.getElementById("grpNum").value = searchResult[i]._source.frm.grp.grp_code;
}
})
}
}
});
}
});
</script>
<form>
<input id="grpName">
<input id="grpNum">
</form>
【问题讨论】:
标签: javascript html json ajax