Cooper
Cooper

Reputation: 103

Change form submission URL based on button clicked

i want to use a button as a link to another page. i have looked around and read some solutions but none worked. i dont want to use action in my form tag because i might want to have couple of buttons as links in that form tag.

here is what i have tried last:(didnt work)

<button onclick="location.href='../ClientSide/Registration/registration.aspx'">register</button>

what am i doing wrong? or is there a better/other way?

i really would like to use only html if possible, if not then to use: javascript or asp.net( i dont know jquery or php)

Upvotes: 1

Views: 7460

Answers (4)

Parker Link
Parker Link

Reputation: 41

Use the formaction="url" tag on the <input> or <button>, as per: https://css-tricks.com/separate-form-submit-buttons-go-different-urls/

Upvotes: 4

Chris Peters
Chris Peters

Reputation: 18090

You cannot do this directly using only HTML.

You have two options:

Option 1 Post the data to a single script on the server that decides what to do based on which button is clicked.

<form action="/some-url.aspx" method="post">
  <button name="button_action" value="register">register</button>
  <button name="button_action" value="another">another</button>
</form>

Then your script at /some-url.aspx would decide what to do next based on the value of button_action.

Option 2 Use JavaScript to change the form's action attribute based on which button is clicked.

<form id="form-with-buttons" action="/some-url" method="post">
  <button id="register-button" data-url="/some-url.aspx">register</button>
  <button id="another-button" data-url="/another-url.aspx">another</button>
</form>

<script>
  $("#register-button, #another-button").click(function(e) {
    e.preventDefault();

    var form = $("#form-with-buttons");

    form.prop("action", $(this).data("url"));
    form.submit();
  });
</script>

Option 1 is more accessible but requires some messiness on the server side. Option 2 is fairly clean but requires JavaScript and a little messiness to work. It really depends on where you want the extra logic and how you feel about the accessibility of your form.

Upvotes: 2

Jagadeesh J
Jagadeesh J

Reputation: 1301

A simple answer would be wrapping the button inside anchor

<a href='../ClientSide/Registration/registration.aspx'>
<button>Click Here</button>
</a>

Upvotes: -2

Arsen Ibragimov
Arsen Ibragimov

Reputation: 435

use jQuery on you page and this code

$(function(){
   $("button").on("click",function(e){
      e.preventDefault();
      location.href='../ClientSide/Registration/registration.aspx';
   })
});

e.preventDefault() makes form NOT SUBMITING

Upvotes: 1

Related Questions