$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i]._source.name + ">" + result[i]._source.name + "</option>");
使用jQuery方式并添加数据属性:
$("#returnedProducts").append($("<option/>",
{
"srindex": i,
"data-attributes": JSON.stringify(result[i]._source.attributes),
"value": result[i]._source.name,
"html": result[i]._source.name,
}
));
通过这种方式,您可以获得您的属性:
var attributes = $('#returnedProducts').find(optSelector).data('attributes');
$("#groupColor").val(attributes.groupColor);
$("#groupCategory").val(attributes.groupCategory);
例如:
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let optSelector = `option[value = '${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ($('#returnedProducts').find(optSelector).length) {
//this one works
$("#groupName").val(_this.val());
//I want to fill these with _source.attributes.groupColor and groupCategory
var attributes = $('#returnedProducts').find(optSelector).data('attributes');
$("#groupColor").val(attributes.groupColor);
$("#groupCategory").val(attributes.groupCategory);
} else {
const searchResult = $(this).val();
$("#returnedProducts").empty();
var result = [{
_source: {
"name": "cat",
attributes: {
"groupColor": "blue1",
"groupCategory": "Misc1",
},
},
}, {
_source: {
"name": "cat1",
attributes: {
"groupColor": "blue2",
"groupCategory": "Misc2",
},
},
}, {
_source: {
"name": "cat2",
attributes: {
"groupColor": "blue3",
"groupCategory": "Misc3",
},
},
}, {
_source: {
"name": "cat33",
attributes: {
"groupColor": "blue4",
"groupCategory": "Misc4",
},
}
}];
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append($("<option/>",
{
"srindex": i,
"data-attributes": JSON.stringify(result[i]._source.attributes),
"value": result[i]._source.name,
"html": result[i]._source.name,
}
));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="productInput" list="returnedProducts">
<datalist id="returnedProducts"></datalist>
<input id="groupName">
<input id="groupColor">
<input id="groupCategory">