2

I've got a search box and a search button. I can hit the search button and the results pop up, no problem, works fine. I wanted to add the ability to search by pressing enter as well, so I added in some code to listen for the keypress and click my button when the keypress is released. This, however, results in the form being submitted and reloads the page with no data. I tried adding in preventDefault() and stopPropagation() to the event listener, but no matter what, the form gets submitted when I hit enter. It shows the correct information for a split second, but then immediately reloads the page.

Here's the HTML:

<script defer src="https://use.fontawesome.com/releases/v5.0.10/js/all.js" integrity="sha384-slN8GvtUJGnv6ca26v8EzVaR9DC58QEwsIk9q1QXdCU8Yu8ck/tL/5szYlBbqmS+" crossorigin="anonymous"></script>

<div class="container-fluid">
  <div class="row search-box" id="firstRow">
    <div class='col-10 search-head-two'>
      <form class="form">
        <input type="text" class="search-input" id="term">
      </form>
    </div>
    <div class='col-2 search-head-one'>
      <button id="search"><i class="fa fa-search"></i></button>
    </div>
    </div>
  </div>
</div>

Here's the Javascript:

var content = [];

document.getElementById("term")
  .addEventListener("keyup", function(event) {
  event.stopPropagation();
  event.preventDefault();
  if (event.keyCode === 13) {
    document.getElementById("search").click();
  }
});

document.getElementById("search").onclick = function() {getData()};

function getData() {
  var domain = "https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=" + encodeURI(document.getElementById('term').value) + "&limit=10";
  fetch(domain).then(function(resp) {
    return resp.json()
}).then(function(data) {
    for (var i = 1; i < data.length; i++) {
      content.push(data[i]);
    }
    var content1 = content[0];
    var content2 = content[1];
    var content3 = content[2];
    for (var x = 0; x < content[0].length; x++) {
      addRow(content1, content2, content3, x);
    }
    console.log(content[0]);
    console.log(content[1]);
    console.log(content[2]);
  });
}

function addRow(content1, content2, content3, x) {
  var div = document.createElement('div');

  div.className = 'row';
  div.innerHTML = '<div class="col-3" id="title">\
                   <p>' + content1[x] + '</p>\
                   </div>\
                   <div class="col-9" id="content">\
                   <p>' + content2[x] + '</br></br><a target="_blank" href="' + content3[x] + '">' + content3[x] + '</a></p>\
                   </div>';
  document.getElementById('firstRow').appendChild(div);
}

Also important to note is that I'm using Bootstrap 4, Jquery and Jquery UI as external scripts. I'm running this in CodePen.io.

Cdhippen
  • 615
  • 1
  • 10
  • 32
  • I'm not even sure why you'd click the button when you could just call the same function. But keep in mind that other listeners (like the default) might not be on keyup, rather keydown or keypress. – Dave Newton Apr 17 '18 at 16:32
  • Ok, so what could I do in the main body of the script to say "Don't ever do the default for this input fields submit"? – Cdhippen Apr 17 '18 at 16:34
  • 1
    Nevermind, I just switched it to keydown, and moved the preventDefault to the if clause and it's working great now! Thanks – Cdhippen Apr 17 '18 at 16:36
  • You could also attach to the form submit. – Dave Newton Apr 17 '18 at 16:37

2 Answers2

1

I moved the event.preventDefault() into the if clause, and changed the eventListener from keyup to keydown since the form was getting submitted on keydown not keyup. Now it works like a charm.

document.getElementById("term")
  .addEventListener("keydown", function(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.getElementById("search").click();
  }
});
Cdhippen
  • 615
  • 1
  • 10
  • 32
0

Check this.

Some usefull MDN infos on preventDefault() Also, you cant have any return from Ajax requests.

Evan
  • 583
  • 1
  • 5
  • 11
  • 2
    Welcome to Stack Overflow. Please read [answer]. _Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline._ – pfx Jun 01 '18 at 13:36