How to create a HTML Cancel button that redirects

2019-02-01 05:44发布

I am playing with the Buttons in the w3schools Tryit editor, and I am trying to figure out how to make my browser redirect to an URL when I click on the "Cancel" button.

Here's what I have tried:

<form action="demo_form.asp" method="get">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <button type="submit" value="Submit">Submit</button>
  <button type="reset" value="Reset">Reset</button>
  <button type="cancel" onclick="javascript:window.location='http://stackoverflow.com';">Cancel</button>
</form>

But it doesn't work. Any ideas?

10条回答
不美不萌又怎样
2楼-- · 2019-02-01 06:14

Just put type="button"

<button type="button"><b>Cancel</b></button>

Because your button is inside a form it is taking default value as submit and type="cancel" doesn't exist.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-01 06:16
<button onclick=\"window.location='{$_SERVER['PHP_SELF']}';return false;\">Reset</button>

Not enough rep to Vote Up for Kostyan. Here's my final solution (needed a reset button).

Thanks again to Kostyan for answering the question as asked without suggesting a "workaround" (time-consuming) method to "construct a button" with styles.

This is a Button (which the viewer expects to see) and it works exactly as requested. And it mingles with the other buttons on the page. Without complexity.

I did remove the "type=cancel" which apparently was useless. So even less code. :)

查看更多
在下西门庆
4楼-- · 2019-02-01 06:16

With Jquery:

$(".cancel-button").click(function (e) {
  e.preventDefault();
});
查看更多
孤傲高冷的网名
5楼-- · 2019-02-01 06:21

Here, i am using link in the form of button for CANCEL operation.

<button><a href="main.html">cancel</a></button>
查看更多
Animai°情兽
6楼-- · 2019-02-01 06:22

it defaults to submitting a form, easiest way is to add "return false"

<button type="cancel" onclick="window.location='http://stackoverflow.com';return false;">Cancel</button>
查看更多
啃猪蹄的小仙女
7楼-- · 2019-02-01 06:25
<input class="button" type="button" onclick="window.location.replace('your_url')" value="Cancel" />
查看更多
登录 后发表回答