简体   繁体   中英

How can my user hit enter or click a button to submit and be redirected?

So I have this html form:

<form>
    <input type="text" placeholder="Equation" id="equation_input" onsubmit="return button_click()"/>
    <input class = "search_button" type="submit" id="search" onclick="button_click()" value="Search"/>
</form>

And I need to take the value the user entered in the equation input, add it to the beginning of a url, and then redirect the user to that newly formed url. I tried this in my script tags:

function button_click() {
    var url = `https://exampleurl.com?q=${document.getElementById('equation_input').value}`;
    window.location.replace(url);
}

I've tried a couple things, but I'm not sure what's causing the problem so I don't know exactly what to try.

No need for any js to do this. It can be done by default form submit by naming the input and setting action and method attributes of the form.

Note that an <input> has no submit event, only a <form> does

<form method="GET" action="https://exampleurl.com">
  <input type="text" placeholder="Equation" id="equation_input" name="q" required/>
  <input class="search_button" type="submit" id="search" value="Search" />
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM