riyaz
riyaz

Reputation: 23

Filter Json data in jquery easyautocomplete

The below code works fine. I am asking for a help that I want to filter the json data, that is I want to display labels of corresponding id which is greater than or equal to 3.

In this case, should display only "India" and "France" in suggestion list.

Please note that I used Easy autocomplete plugin.

Would really appreciate if anyone can help me with this. Thanks in advance

below is my json file

countries.json

[
{
"id": "0.1",
"label": "America" },{
"id": "0.9",
"label": "UAE" },{
"id": "3.2",
"label": "India"},{
"id": "3.02",
"label": "France" } ]

HTML is

index.php

<div class="form-group">
                    <input id="city" type="text" name="city" class="form-control" />
                </div>

and script is:

script.js

$(function() { var options = { url: "../review/countries.json", getValue: function(element) {
 return element.label; list: {
match: {
  enabled: true
} }; $("#city").easyAutocomplete(options);

Upvotes: 2

Views: 5122

Answers (2)

ADreNaLiNe-DJ
ADreNaLiNe-DJ

Reputation: 4919

Here is the code to iterate throw the array of items:

var options = [
    { "id": "0.1", "label": "America" },
    { "id": "0.9", "label": "UAE" },
    { "id": "3.2", "label": "India"},
    { "id": "3.02", "label": "France" }
];

var filtered = new Array();
$.each(option, function(index, item) {
    if(item.id >= 3) {
        filtered.push(item);
    }
});

Note: You'll need to load options variable with a GET ajax request on the json file and use filtered instead of options in your autocomplete.

Here is a complete example with ajax loading:

$(document).ready(function(){
    $.getJSON("../review/countries.json", function(data) {
        var filtered = new Array();
        $.each(option, function(index, item) {
            if(item.id >= 3) {
                options.push(item);
            }
        });
        var options = {
            data: filtered
        };
        $("#city").easyAutocomplete(options);
    }
});

Upvotes: 1

G&#246;rkem D.
G&#246;rkem D.

Reputation: 551

Try this out,

$(function() {

  var options = {
    url: "../review/countries.json",
    getValue: function(element) {
      var id = parseFloat(element.id);
      if (id > 3) {
        return element.label;
      } else {
        return '';
      }

    },
    list: {
      match: {
        enabled: true
      }

    }

  };
  $("#city").easyAutocomplete(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://easyautocomplete.com/dist/jquery.easy-autocomplete.min.js"></script>
<div class="form-group">
  <input id="city" type="text" name="city" class="form-control" />
</div>

Upvotes: 2

Related Questions