Search code examples
javascriptjqueryhtmlmediawiki-api

How to replace current page content on user input?


I am creating a search engine of sorts, using the Wikipedia API to query content. As it currently stands, the user can make a search input and the page returns the top 10 results with links and snippets. I run into difficulty when the user makes another search, in which case the page simply appends the original search results again. I have tried using replaceWith() and html(), but they either prevent the search results from coming through at all (if I put them within the event handler), or they don't get triggered (if they are outside the event handler). I am hoping to achieve a result where the user can make another input and the page will replace the current content with the new search results.

Here is what I have currently:

JS:

var results = [];

$("#search").on("keydown", "#searchinput", function(event) {
  if (event.key === "Enter") {
    var searchParameter = encodeURIComponent(this.value);
    var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";
    $.getJSON(link, function(data) {
      for (var key in data) {
        results.push(data[key]);
      }
      for (var i = 0; i < 10; i++) {
        $("#results").append("<div class=\"resultContent\">" + "<h2>" + "<a href=\"" + results[3][i] + "\">" + results[1][i] + "</a>" + "</h2>" + "<p>" + results[2][i] + "<br/>" + "</p>")
      }
    })
  }
})

HTML:

<a href="https://en.wikipedia.org/wiki/Special:Random">Feeling Bold? Click Here for a Random Article</a>

<div id="search">
  <span>Search:</span>
  <input type="text" id="searchinput" autocomplete="off"></input>
</div>

<div id="results"></div>

Thanks for the help!


Solution

  • You can remove the current results just before your loop:

    $("#results").empty();    
    for (var i = 0; i < 10; i++) {
         $("#results").append("<div class=\"resultContent\">" + "<h2>" + "<a href=\"" + results[3][i] + "\">" + results[1][i] + "</a>" + "</h2>" + "<p>" + results[2][i] + "<br/>" + "</p>")
    }