0

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?

Ele975
  • 352
  • 3
  • 13
  • Why don't you try the form submit and button type as submit... you can also handle the submission there as per your needs. – Anil Parshi Dec 01 '21 at 11:21
  • In your current situation when you enter it's submitting the form and passing your textbox value `name="search"` using the get method to some random URL or the current URL. – Anil Parshi Dec 01 '21 at 11:23
  • Just update `
    ` and use `e.preventDefault();` inside your `searchFile()` function.
    – Anil Parshi Dec 01 '21 at 11:52

1 Answers1

1
  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>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I tried to use your code trying to implement it step by step, then in my js file there is only the part you wrote, but the problem is that it cannot find the element because it says: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener'). It seems it cannot see document.querySelector('.example') – Ele975 Dec 01 '21 at 14:18
  • @ElenaFranchini https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Quentin Dec 01 '21 at 15:04
  • Thank you so much, I used type="module" on the script in html and it worked – Ele975 Dec 01 '21 at 18:38