简体   繁体   English

防止HTML中的页面重定向按钮

[英]Prevent button to page redirect in html

I have a few buttons and a submit button. 我有几个按钮和一个提交按钮。 (Making simple) My idea is to receive the value of the clicked button using a php and display it only when submit . (简单)我的想法是使用php来接收clicked按钮的值,并仅在Submit时显示它。 Here I face a problem that button click itself redirects to the page and displays the value (means it is not waiting for the submit button to press). 在这里,我遇到一个问题,即按钮单击本身会重定向到页面并显示值(意味着它不等待提交按钮被按下)。 I followed a javascript provided here . 我遵循了这里提供的JavaScript。 But didn't work. 但是没有用。 Any method to achieve this? 有什么方法可以做到这一点?

<form action="calculate.php" method="POST">

<button type="" name="btn" style="background-color:#7F77AE" value="Alf">x1</button>
<button type="" name="btn" style="background-color:#7F77AE" value="ABI">y1</button>
<button type="" name="btn" style="background-color:#7F77AE" value="APE">z1</button>

<input type="submit" value="Submit">

php part is as simple as, php部分非常简单,

 $button = $_POST['btn']; 
 echo $button;

Define the plain button's type as "button" 将普通按钮的类型定义为“按钮”

<form action="calculate.php" method="POST">

<button type="button" name="btn" style="background-color:#7F77AE" value="Alf">x1</button>
<button type="button" name="btn" style="background-color:#7F77AE" value="ABI">y1</button>
<button type="button" name="btn" style="background-color:#7F77AE" value="APE">z1</button>

<input type="submit" value="Submit">

EDIT: If you absolutely need to use buttons here you can do something like this: 编辑:如果您绝对需要在这里使用按钮,则可以执行以下操作:

<script>
function select(val){
    document.getElementById("btnValueStore").value = val;
}
</script>

<form action="calculate.php" method="POST">
<button type="button" style="background-color:#7F77AE" onClick="select('Alf')">x1</button>
<button type="button" style="background-color:#7F77AE" onClick="select('ABI')">y1</button>
<button type="button" style="background-color:#7F77AE" onClick="select('APE')">z1</button>
<input type="hidden" value="" name="btn" id="btnValueStore">
<input type="submit" value="Submit">
</form>

First you define a hidden input to hold the value of the last pressed button. 首先,您定义一个隐藏的输入来保存最后按下的按钮的值。

The select function changes the value of the hidden input field to whatever value you pass it. select函数会将隐藏输入字段的值更改为您传递它的任何值。

For each of your buttons set the "onClick" property to call the select function with the corresponding button's value. 为每个按钮设置“ onClick”属性,以使用相应按钮的值调用选择功能。

Note: This particular implementation allows only 1 button to have been "selected" (the last one you clicked) - for the ability to "select" more than one button you will need multiple hidden input fields. 注意:此特定实现仅允许“选择”一个按钮(单击的最后一个按钮)-为了能够“选择”多个按钮,您将需要多个隐藏的输入字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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