Search code examples
javascripthtmleventskeypressenter

Prevent default on enter key with a button in Javascript


I have my HTML code:

<!DOCTYPE html>
<head>
  <script src="../req.js"></script>
  </head>


<link rel="stylesheet" href="style.css">
<html>

<body>
  <h1> Recipes founder</h1>
  <form class="example">
    <input id ="query" type="text" placeholder="Insert a recipe.." name="search" value="">
    <button id="searchRecipe" type="button" onkeydown="handler(e)" onclick="searchFile()"><i></i>Search</button>

  </form>
  <div id="content"></div>
</body>
</html>

and my js code associated with it:

function searchFile(e) {
  // enter must do the same
  const q = document.getElementById('query').value;
  const total_q = `Title%3A${q}%20OR%20Description%3A${q}%20OR%20web%3A${q}`
  fetch(
`http://localhost:8983/solr/recipe/select?indent=true&q.op=OR&q=${total_q}&rows=300`, { mode: 'cors' }

  ).then((res) => res.json())
      // Take actual json
      .then(({ response }) => appendData(response))
      .catch(function (err) {
          console.log(err)
      });
  }

function appendData(data) {
    // clear previous research
    document.getElementById("content").innerHTML = "";
    let docs = data.docs;
    // Take each element of the json file
    for (elem of docs) {
        var mainContainer = document.getElementById("content");
        // title recipe
        var a1 = document.createElement("a");
        a1.setAttribute("href", elem.url);
        var div = document.createElement("div");
        div.innerHTML = elem.Title;
        a1.appendChild(div);

        // insert image of recipe and link for page in website
        var a = document.createElement("a");
        a.setAttribute("href", elem.Image);
        var img = document.createElement("img");
        // img.setAttribute("href", elem.url);
        img.setAttribute("src", elem.Image);
        a.appendChild(img);

        // recipe description
        var p = document.createElement("p");
        p.innerHTML = elem.Description;
        // Insert elements in dev
        mainContainer.appendChild(a1);
        mainContainer.appendChild(p);
        mainContainer.appendChild(a);
        
    }
}


function handler(event) {
    if (event == "click") {
       searchFile();
    }
    else if ((event.keyCode || event.which) == 13){
        event.preventDefault();
        event.cancelBubble = true;
        event.returnValue = false;
        event.stopPropagation();
        event.preventDefault();

        searchFile();
    }
    else {
        console.log("Nothing")
    }
}

What searchFile() and appendData() do is not important because they work. The target is when the user clicks on the search button or presses the enter key, searchFile() must be called. Clicking on the search button works, but the problem is when a user clicks enter, it navigates to http://localhost:8000/?search=SOMETHING (depends on what the user inserted) . I think it is the default behaviour of the enter key, I tried to prevent it using different codes but nothing works. I read that instead of using the event onkeypress we have to use onkeydown but I'm still in the same situation. I tried also to wait for the DOM to be loaded but nothing. Does someone have an idea about it?


Solution

    1. Remove all the event handlers on the button
    2. Make the button a submit button
    3. Use the submit event on the form (this will trigger if the form submission is trigged by enter in the input or the button being clicked or enter being pressed over the button)
    4. Prevent the default event behaviour (so the form data isn't submitted to a URL which the browser navigates to)
    5. Don't bother doing any tests to try to figure out if it was a click or something else, all that matters if that the form was submitted.

    const submitHandler = (event) => {
        event.preventDefault();
        alert("You can do your ajax search here");
    };
    
    document.querySelector('.example').addEventListener('submit', submitHandler);
      <form class="example">
        <input id="query" type="text" placeholder="Insert a recipe.." name="search" value="">
        <button>Search</button>
      </form>