2

Sorry if this is a dumb question, I have a form in my HTML document and I want to put the text that you submit from the form into my Javascript API call.

<form id="form">
 <input type="text" id="query" name="keyw">
 <button>Search</button>
</form>

I need to get the output from this into the [USER TEXT HERE] part

 fetch("https://example.com/search?keyw=[USER TEXT HERE]")
 .then((response) => response.json())

How would I do that? Thanks.

quin
  • 21
  • 3

2 Answers2

0

In Javascript we can create an event listener for onSubmit:

document.getElementById("form").addEventListener("submit", fetchSomeAPI);

Inside the fetchSomeAPI function it's just a matter of concatenating the user's input and the request:

function fetchSomeAPI() {
    fetch(`https://example.com/search?keyw=${document.getElementById("query").value}`)
    .then((response) => response.json())
}
-1

To get the value from the form, you need to listen for a keypress event on that <input /> to make sure that the value is updated every time the user interacts with the input. Something like: https://codesandbox.io/s/example-quin-g5z54m

  • Note that on Stack Overflow we require that code is shared on Stack Overflow in addition to any external sites like Code Sandbox. – Heretic Monkey Dec 23 '22 at 22:28