Neither .preventDefault() nor .stopPropagation() prevent the page from reloading when the submit button is clicked


Cdhippen

I have a search box and a search button. I can click the search button and the results pop up, no problem, it works. I also wanted to add search functionality by pressing enter, so I added some code to listen for key presses and click my button when the key is released. However, this will cause the form to be submitted and the page to reload with no data. I tried adding preventDefault() and stopPropagation() to the event listener, but no matter what, the form is submitted when I press enter. It displays the correct information within a second, then immediately reloads the page.

Here is 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 is 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 am using Bootstrap 4, Jquery and Jquery UI as external script. I am running it in CodePen.io.

Cdhippen

I moved event.preventDefault() into the if clause and changed the eventListener from keyup to keydown since the form is submitted via 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();
  }
});

Related


Ruby on Rails page not reloading when submit button is clicked

white I have an approve button that changes statusproperties of a table record Shop. When I click it, it does change the properties, but it doesn't reload the page, so I have to manually reload the page to see the results, which is very inconvenient. It looks

Web page refreshes when submit button is clicked

television Every time I enter data in the fields and click submit, the page refreshes, clearing the form, instead of typing on an external Javascript file. But when I changed the button type to "Button" instead of "Submit", everything went fine except the "Req

When reloading Slider, neither forward nor back has effect

Lucas Santos I am using bxSlider and in the following situation When a specific year is selected, I need to reload the month and just have the month in the clicked year value. My problem is that when reloading, I let go of the arrow controls, i.e., I can't mov

When reloading Slider, neither forward nor back has effect

Lucas Santos I am using bxSlider and in the following situation When a specific year is selected, I need to reload the month and just have the month in the clicked year value. My problem is that when reloading, I let go of the arrow controls, i.e., I can't mov

When reloading Slider, neither forward nor back has effect

Lucas Santos I am using bxSlider and in the following situation When a specific year is selected, I need to reload the month and just have the month in the clicked year value. My problem is that when reloading, I let go of the arrow controls, i.e., I can't mov

UpdatePanel doesn't prevent button from reloading page

I'm just Andrew I just wanted to simplify an example of this problem by making a short prototype to test the UpdatePanel functionality to disable ASP.NET page reloads when a link button is clicked . I've seen this approach in questions like this one . To test

How to prevent button from moving when clicked?

JustAnotherSimpleProgrammer__ I have the following code: <!DOCTYPE html> <html> <body> <head> <script> function Show(element){ element.style.display = "block"; } function Hide(element){ element.style.display = "none"; } function Slide(){ try{ img1 = im

How to prevent button from moving when clicked?

storm I have several buttons in a div that will display a value once clicked. The problem I'm having is: After a button is clicked and a value is displayed, it also moves down. I'm not sure how to prevent this from happening. Can someone help? Here is a link t

Prevent VBE from opening when button is clicked

TKE-439 I have some buttons that run some code, and every time the button is clicked, the VBE opens, which I don't need to do. I've tried it Application.VBE.MainWindow.Visible = Falsein a few different locations (some not shown here), but that doesn't stop any

How to prevent button from moving when clicked?

JustAnotherSimpleProgrammer__ I have the following code: <!DOCTYPE html> <html> <body> <head> <script> function Show(element){ element.style.display = "block"; } function Hide(element){ element.style.display = "none"; } function Slide(){ try{ img1 = im

Prevent VBE from opening when button is clicked

TKE-439 I have some buttons that run some code, and every time the button is clicked, the VBE opens, which I don't need to do. I've tried it Application.VBE.MainWindow.Visible = Falsein a few different locations (some not shown here), but that doesn't stop any

Prevent div from shaking when button is clicked

Orahmax I added a border-bottom to the button, removed the border-bottom when the button was clicked, and moved the button 3px down to create a press effect. However, when the button is clicked, the div below the active div also moves up and down. This screens

How to prevent button from moving when clicked?

JustAnotherSimpleProgrammer__ I have the following code: <!DOCTYPE html> <html> <body> <head> <script> function Show(element){ element.style.display = "block"; } function Hide(element){ element.style.display = "none"; } function Slide(){ try{ img1 = im