php 单击时获取按钮值并回显它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17186157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:26:39  来源:igfitidea点击:

Getting button value on click and echo it

php

提问by user2500189

i am a beginner in php and my first task is to build a calculator and I am here to ask how to get a value from a button and just echo it on the same page. I am trying through method post using isset but enable to display any value on the same page.

我是 php 的初学者,我的第一个任务是构建一个计算器,我在这里询问如何从按钮获取值并在同一页面上回显它。我正在尝试使用 isset 进行方法发布,但可以在同一页面上显示任何值。

<form action="" method="POST">
<input type="button" value="0" name="zero">
</form>


<?php 
   if (isset($_POST["zero"]))
   {

    echo $_POST["zero"];
}
?>

回答by MrCode

Only an input[type=submit]will submit the form onclick. It is valid to have multiple submit buttons:

只有一个input[type=submit]将提交表单onclick。有多个提交按钮是有效的:

<form action="" method="POST">
    <input type="submit" value="0" name="mybutton">
    <input type="submit" value="1" name="mybutton">
    <input type="submit" value="2" name="mybutton">
</form>

<?php 
   if (isset($_POST["mybutton"]))
   {
       echo $_POST["mybutton"];
   }
?>

If you want to use input[type=button]then you will need some Javascript to trigger the submit, and a hidden input to transport the value.

如果你想使用,input[type=button]那么你需要一些 Javascript 来触发提交,以及一个隐藏的输入来传输值。

<script>
window.onload = function(){
    document.getElementsByName("mybutton").onclick = function(){
        document.getElementsByName("postvar")[0].value = this.value;
        document.forms.myform.submit();
    }
};
</script>

<form name="myform" action="" method="POST">
    <input type="hidden" name="postvar" value="" />

    <input type="button" value="0" name="mybutton">
    <input type="button" value="1" name="mybutton">
    <input type="button" value="2" name="mybutton">
</form>

<?php 
   if (isset($_POST["postvar"]))
   {
       echo $_POST["postvar"];
   }
?>

回答by swapnesh

Change

改变

<input type="button" value="0" name="zero">

To

<input type="submit" value="0" name="zero" />

Add an event handlerif you want to do it via buttonclick.

event handler如果您想通过button单击添加一个。

回答by Subhra Sekhar Mukhopadhyay

Try this

尝试这个

<form action="" method="POST">
    <input type="submit" value="0" name="zero">
    </form>


    <?php 
       if (isset($_POST["zero"]))
       {

        echo $_POST["zero"];
    }
    ?>

回答by twitch

Use 
<input type="submit" value="0" name="zero">
else if you want to use button use javascript

<form action="" method="POST">
<input type="button" value="0" name="zero">
</form>

<script type="text/javascript">
$("input[type='button']").click(function(){
alert(this.value);
});
</script>