I have successfully implemented the jQuery Autocomplete function in my HTML input filed, it returns an array of JSON objects, what I would like to achieve is the following:
So, here's my js code:
$.ajax({
url: "<?php echo $pointerClass ?>.json",
type: "POST",
dataType: "JSON"
}).done(function(data){
var jsonData = data;
var arr = new Array();
var keys = Object.keys(jsonData);
for(var i=0; i<keys.length; i++){
var key = keys[i];
var jString = JSON.stringify(jsonData[key]);
arr.push(jString);
}// ./ for
console.log('arr: ' + arr[0]);
// autocomplete jquery function
$( "#ar-type-pointer-objID" ).autocomplete({
source: arr,
minLength: 1
});
});
Here's a screenshot of my drop-down menu:
As you can see by the red frame, I need to click on an item and pass only the "objID"
value to my input field, so it'll be "qO19zg8mV4"
since I'm clicking on the row in the red square.
Here's how my input should look like after clicking on a drop-down's row:
According to the autocomplete documentation, you have two interesting events: select and close.
select is
Triggered when an item is selected from the menu. The default action is to replace the text field's value with the value of the selected item
close is:
Triggered when the menu is hidden. Not every close event will be accompanied by a change event.
Select has two parameters:
ui is an object like this:
item: {
label: string,
value: string
}
Not sure where you will get your JSON, probably value, so I assume that...do a console.log to be sure of it!
You should rewrite with something like
$( "#ar-type-pointer-objID" ).autocomplete({
source: arr,
select: function(event, ui) {
const target = event.target;
const val = JSON.parse(ui.item.value); // Check if decode is needed or is already passed as an object
jQuery(target).val(val.ObjID);
event.preventDefault();
return false;
}
});
We prevent the default, because "The default action is to replace the text field's value with the value of the selected item." and your change in the input field will be lost. You still have to manage some info by yourself but the idea should be enough!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.