简体   繁体   中英

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 . 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 . 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,

 $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.

For each of your buttons set the "onClick" property to call the select function with the corresponding button's value.

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.

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