0

Recently I'm studying jQuery . I wish that when I write here <input type="text" id="scrivo" /> I want to filter an array derived from a json file. The json file is like this:

{
  "Re": 
[
  {
    "nm": "Edward the Elder",
    "cty": "GB",
    "hse": "House of Wessex",
    "yrs": "899-925"
  },
  {
    "nm": "Edgar",
    "cty": "GB",
    "hse": "House of Wessex",
    "yrs": "959-975"
  },
  {
    "nm": "Edward the Martyr",
    "cty": "GB",
    "hse": "House of Wessex",
    "yrs": "975-978"
  }
 ]
}

and the piece of code is this:

<script language="JavaScript">
$(document).ready(function()             
    {
      $('#scrivo').keyup(function()
        {
         var json = (function () {
         var json = null;
         $.ajax({
             'async': false,
             'global': false,
             'url': "re.json",
             'dataType': "json",
             'success': function (data) {
                 json = data;
             }
               });
             return json.Re;
         })();
         var o = $.grep(json, function (n) { return (n.nm.indexOf("El")) },true);
      });
 });
</script>

For example I would like to filter the objects that contain "El", which is the first object in the json file. Instead I do not receive anything. Can you help me please?

AlessandroG
  • 318
  • 5
  • 14
  • 1
    Forget my older comment, I didn't see you were using `async : false`. Maybe [**this question**](http://stackoverflow.com/questions/1531693/ajax-async-false-request-is-still-firing-asynchronously) will help you? – blex Jul 26 '14 at 15:57
  • ajax is asynchronous. You first return json.re, which is not defined, and after a while response comes from server. – Ivan Ivanov Jul 26 '14 at 16:02
  • 1
    why ``async:false``?? – Ehsan Sajjad Jul 26 '14 at 16:02
  • 1
    It's because `return n.nm.indexOf("El")` should be `return n.nm.indexOf("El") !== -1`. The `indexOf` method returns an index, which is `-1` when no match is found. So the first object returns a higher index and all the others return `-1`, all of which are "truthy" values. This means the condition always passes, and because you passed `true` as the third argument to `$.grep`, the condition is inverted, removing excluding all items. – cookie monster Jul 26 '14 at 16:18

1 Answers1

1

I found the bug: You have inverted the grep command. Here's a jsFiddle demonstrating my answer: http://jsfiddle.net/UqE5n/3/

The crucial line is here:

var value = $('#scrivo').val();
var o = $.grep(jsonRe, function (n) {
    return n.nm.indexOf(value) >= 0;
}, false);                                <--- "true" will invert the result!

It will also guide you how to use jsFiddle for asking with a code example. I am learning jsQuery myself, so thanks for the question!

sina72
  • 4,931
  • 3
  • 35
  • 36