1

I have the below code, which you can search in the input and list of data will be in a drop down. but I want to know how I can change this to get the data from the JSON file instead of writing the list in <li><a>...

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>

  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>

  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

<script>
function myFunction() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";

        }
    }
}
</script>
2
  • Let me confirm , json file or json data ... Commented Jun 5, 2018 at 15:13
  • I have this now on index.html file and the data.json in same folder Commented Jun 5, 2018 at 15:50

2 Answers 2

1

First you can create the external file (example "data.json"):

[
    {"name":"Adele", "href":"#"},
    {"name":"Agnes","href":"#"},
    {"name":"Billy","href":"#"},
    {"name":"Bob","href":"#"},
    {"name":"Calvin","href":"#"},
    {"name":"Christina","href":"#"},
    {"name":"Cindy","href":"#"}
]

Then, you can define a function to update the UI with a data array:

function updateList(data) {
    var ul = document.getElementById('myUL');
    for (i = 0; i < data.length; i++) {
        var a = document.createElement('a');
        a.appendChild(document.createTextNode(data[i].name));
        a.setAttribute('href', data[i].href);
        var li = document.createElement('li');
        li.appendChild(a);
        ul.appendChild(li);
    }
}

You can import the json file using an AJAX request with native javascript:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (this.readystate == 4 && this.status == 200) {
        var data = JSON.parse(this.responseText);
        updateList(data);
    }
};
request.open("GET", "data.json", true);
request.send();

This code would then populate the existing UI element from the page:

<ul id="myUL"></ul>
Sign up to request clarification or add additional context in comments.

10 Comments

Your data.json is not valid json, it's an javascript array of objects
thanks, do I still need to add <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
I updated to ensure a valid JSON file and to load it properly with an AJAX request. Thanks @baao for catching my mistake.
Yes, @charlie97, this will still work with your search code
I edited it for you. Now it's valid json. You need to enclose everything in " (also the keys), and ' is not valid
|
0

Try this :

 var jsonObj = [
    {"name":"Adele","link":"Adele.html"},
    {"name":"Agnes","link":"Agnes.html"},
    {"name":"Billy","link":"Billy.html"},
    {"name":"Bob","link":"Bob.html"},
    {"name":"Calvin","link":"Calvin.html"},
    {"name":"Christina","link":"Christina.html"},
    {"name":"Cindy","link":"Cindy.html"}
]
 
 for(i=0; i < jsonObj.length; i++)
 {
   var li=document.createElement('li');
   li.innerHTML="<a href='"+ jsonObj[i].link +"'>"+ jsonObj[i].name +"</a>";
   document.getElementById('myUL').appendChild(li);
 }
 
document.getElementById('myInput').addEventListener('keyup', function(e) {
    var filteredResult = jsonObj.filter(obj => {
      return obj.name.includes(e.key) === true;
    });
    document.getElementById('myUL').innerHTML = '';
     for(i=0; i < filteredResult.length; i++)
     {
       var li=document.createElement('li');
       li.innerHTML="<a href='"+ filteredResult[i].link +"'>"+ filteredResult[i].name +"</a>";
       document.getElementById('myUL').appendChild(li);
     }
});
<input type="text" id="myInput" placeholder="Search for names.." title="Type in a name">

<ul id="myUL"></ul>

7 Comments

thanks for this, I did paste all this code into my index.html file with the script inside the script tags but when I open on browser, the console says : Cannot read property 'appendChild' of null and it doesnt work, what is the issue? am i missing something
Make sure your ul element should have id="myUL" as we are append the child on this id only.
is there a way to add the keydown method to this function so user can select option with keyboard arrows please?
i used the above code but now i realised that the search brings a random name like cindy when i type ad, is it just searching for a letter within the words? the search isnt working well.
@charlie97 As there is no dropdown to select the options. we have only one search box. Hence, only keyup event will work in that case.
|

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.