简体   繁体   中英

How to filter a JSON array in autocomplete jquery and show a dynamic value in JavaScript?

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:

  1. click on an item of the dropdown list
  2. filter such item's string to get only the objID string.

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:

  1. event
  2. ui

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM