0

<form action="/users" method="GET">
    <input type="text" id="username" name="username" required><br>
    <button type="submit">Search</button>    
    <a href='/users'><button>Clear</button></a>
</form>

when I click on anchor tag form gets submitted, I dont want form to get submitted on anchor tag click. When I take anchor tag out of form it doesnt submit.

What I want is to have anchor tag in the form and not get submitted on anchor tag click, it should get submitted only when button is clicked.

2 Answers 2

5

Buttons inside a form gets submitted on click by default. You can specify type="button" to prevent the form from being submitted when the button is clicked (as in the 1st snippet below)

The anchor tag, as well as the button, BOTH AT THE SAME doesn't seem to be required there. You can remove the anchor tag if it's not required! In this below snippet, the form will not be submitted, but the page will be redirected to /users (that's why page goes blank after it's clicked)

<form action="/users" method="GET">
    <input type="text" id="username" name="username" required><br>
    <button type="submit">Search</button>    
    <a href='/users'><button type="button">Clear</button></a>
</form>

If you want to clear the form when the clear button is clicked, use type="reset"

<form action="/users" method="GET">
    <input type="text" id="username" name="username" required><br>
    <button type="submit">Search</button>    
    <button type="reset">Clear</button>
</form>

2
  • I want the form to get submitted on button type="submit" only and http redirect on anchor tag clicked, problem is when I click anchor tag the url parameters are not getting reset. Apr 9, 2021 at 4:38
  • 1
    URL parameters? Can you try <button type="button" onclick="location.href='/users';">Clear</button>? Or else you can just use the anchor tag and make it look like a button using CSS.
    – Ajith Gopi
    Apr 9, 2021 at 4:41
1

Simply because you are using a Button tag inside Anchor Tag. by-default form triggered on Button when clicked

1
  • you are right I never noticed, but then I remembered my css is based on button so I cant remove it from anchor tag. Apr 9, 2021 at 5:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.