0

I'm new to jQuery and JSON (when you look at my code below you'll quickly see how new I am).

I've got a JSON file and I want to allow users to input a search term (which will be a key in JSON file)) and have the corresponding JSON value be displayed on the web page.

I've searched this forum and the web and, using examples I've found, I've hacked together a script and some HTML but, surprise!, it's not working. I have a rough idea of what the script is doing but I'm finding it very difficult to sort out what is wrong.

Hoping someone can help.

HTML:

<input type="search" name="search" id="search">

jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>

$('#search').keyup(function() {
    var searchField = $('#search').val();
    var myExp = new RegExp(searchField, "i");
    $.get('products.json', function(data) {
        var output = '<ul class="searchresults">';
        $(data).find(searchField).each(function(index, value){
            var val = value.firstChild.nodeValue;
            if ((val.search(myExp) != -1)) {
                output += '<li>' + val + '</li>';
            }       
        });
        output += '</ul>';
        $('#result').html(output);
    });  
});

</script>

JSON (products.json)(The JSON file will be longer than this. I've simplified it):

{"colors":[
    {"A":"red"},
    {"B":"green"},
    {"C":"blue"}
]}

So, if a user types 'B' into the HTML searchfield, I want 'green' to be displayed on the web page.

3
  • so you only want to search the 'colors' field in products.json? if yes, I can give you a simple answer Commented Jul 12, 2016 at 3:48
  • check this demo Commented Jul 12, 2016 at 3:49
  • 1
    @guradio. Thank you! Checked your demo and as a result got my code working. Much appreciated! Not sure that I can vote for your answer since it's a comment but thanks again. Commented Jul 12, 2016 at 4:34

4 Answers 4

1

Please try this:

$('#search').keyup(function() {
    var searchField = $('#search').val();
    $.getJSON('https://api.myjson.com/bins/59t77', function(data) {
    console.log(data);
        var output = '<ul class="searchresults">';
        $.each(data.colors, function(k, obj) {
            if(obj[searchField]) {
                output += '<li>' + obj[searchField] + '</li>';
            }
        });
        output += '</ul>';
        $('#result').html(output);
    });  
});

With some more explanation on your specific issue, I may be able to assist you in better alternatives.

Demo: https://jsfiddle.net/iRbouh/0z228fya/

Sign up to request clarification or add additional context in comments.

5 Comments

@Ha Tim Thanks for your reply.
@ Ismail RBOUH Tried your code but still no success. I have set up a Codepen at [link]codepen.io/Ben10/pen/GqOkRE. JSON is loaded as another Pen. If you have a chance, maybe you could take a look and suggest what I've done wrong. Much appreciated.
I have used the answer from guradio (comment above) but thanks for your suggestion.
@ Ismail RBOUH Answers are coming in so fast I can't keep up. OK, I have checked your demo and, using it as a basis, I have got my script working. Your script loads external JSON file which is particularly helpful for me since that is what I originally intended to do. Thanks for your help. Much appreciated!
@ Ismail RBOUH I've accepted your answer but can't upvote as, since I'm new to Stack Overflow, I don't have sufficient credits. Thanks again.
0

Simple code:

if (typeof json.colors['B'] != 'undefined') {
    console.log(json.colors['B']);
}

1 Comment

I have used answer from@ guradio (comment above) but thanks for your suggestion.
0

try this:

$('#search').keyup(function() {
var searchField = $('#search').val();
var output = '<ul class="searchresults">';
$.get('products.json', function(data) {
    jQuery.each(data.colors, function(i, val) {
        jQuery.each(val, function(i1, val1) {
            if(i1==searchField){
                output += '<li>' + val1 + '</li>';
            }
        });  
    });
    output += '</ul>';
});
$('#result').html(output); 

});

1 Comment

I have used answer from guradio (comment above) but thanks for your suggestion.
0

You can use grep for filter data from array of object as below.

http://manojmahato.com.np/javascript/jquery-remove-item-array-objects-jquery/

var id = 1;
var result = $.grep(data, function(e){
return e.id != id;
});

This filter data from json but in your case you have to filter object from array for key so you can use each as

var data = {"colors":[
    {"A":"red"},
    {"B":"green"},
    {"C":"blue"}
]};

var result=[];
var SeacrchKey="A";
$.each( data.colors, function( key, value ) {
 if (SeacrchKey in value)
   result.push(value);
});
console.log(result)

Then you can bind result as required. result contain array of filtered object

2 Comments

What does this have to do with OP code? OP has no id in data and how would this get integrated?
@charlietfl there is another idea to filter object per key. i have explained it in answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.