Home > Mobile >  How to get form input to appear as query params when div is click instead of button
How to get form input to appear as query params when div is click instead of button

Time:12-14

I have an html form that is more or less the following

<form action="/results">
 <input name="q" type="text">
 <div>See results</div>
</form>

If I type something into the form, such as "my search" and press "enter" I'll be taken to the Results page with something like this: mywebsite.com/results?q=my search. My problem is that I would like to get the same behavior when someone clicks "See results," which currently takes them to the Results page but without the params. I know using <button> instead of <div> would get me the results I need, but in this situation using <button> is not practical due to how all of the templates have been written.

CodePudding user response:

Concatenate ?q=searchstring to the URL when assigning to window.location.

document.querySelector("#results").addEventListener("click", function() {
  let param = document.querySelector([name=q]).value;
  let url = `/results?q=${encodeURIComponent(param)}`;
  window.location = url;
}
<form action="/results">
 <input name="q" type="text">
 <div id="results">See results</div>
</form>

CodePudding user response:

If you can use input type submit, try wrapping the it in the div as in this way:

<form action="/results">
    <input name="q" type="text">
    <div><input type="submit" value="See results" /></div>
</form>

If this not works for you, alternatively you can handle it using javascript as @Barmar answered above.

  • Related