0

I'm working on the wikipedia viewer for free code camp and I'm trying to make the search bar work.

Ideally I would just like to have the user type in some text, then have that become a string in my code when the user hits submit. This is the html for the search bar so far

<form method="get">
      <input type="text" placeholder="Search articles" class="srchbox" name="Search" id="searchbar">
      <button type="submit" class="btn">Search</button>
</form> 

and the api setup I have to make the search

var apiURL = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&generator=search&search=" + textInput;

$(document).ready(function() {  
  $.ajax({
    url: apiURL,
    dataType: "jsonp",
    success: function(data) {
      var wikiAPI = JSON.stringify(data, null, 3);
      console.log(wikiAPI);  

      var wikiHTML = "";

        for (i=0; i < data[1].length; i++)
        {
          wikiHTML += ("<a href =\"" + data[3][i] + "\" target=\"_blank\">")
          wikiHTML += "<div class = \"wikicontent container-fluid\" style = \"color:black;\">";
          wikiHTML += ("<h2>" + data[1][i] + "</h2>");
          wikiHTML += ("<h3>" + data[2][i] + "</h3>");
          wikiHTML += "</div></a>"
        }
      $("#articles").html(wikiHTML);

I'm a bit lost on how to pull this off so any help would be great. Thank you!

Payton
  • 11
  • 1

1 Answers1

0

You can use submit event, set query to #searchbar .value

$("form").on("submit", function(e) {
  e.preventDefault();
  if (this.searchbar.value.length) {
    var url = "https://en.wikipedia.org/w/api.php?format=json"
              + "&action=opensearch&generator=search&search=" 
              + this.searchbar.value;
    $.ajax({url:url, /* settings */});
  }
});
guest271314
  • 1
  • 15
  • 104
  • 177
  • @Payton See also [How to query and save link in array to call later?](http://stackoverflow.com/questions/40496653/how-to-query-and-save-link-in-array-to-call-later/) – guest271314 Feb 06 '17 at 08:46
  • How do I set the query I'm not sure what that means – Payton Feb 06 '17 at 08:47
  • @Payton `this.searchbar.value` represents the text value of user input at `` which is the value concatenated to `"&search=" + this.searchbar.value` to form a key, value pair. See also http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144 – guest271314 Feb 06 '17 at 08:50