user2500189
user2500189

Reputation: 47

Getting button value on click and echo it

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.

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


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

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

Upvotes: 5

Views: 55052

Answers (4)

MrCode
MrCode

Reputation: 64536

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

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

<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"];
   }
?>

Upvotes: 9

twitch
twitch

Reputation: 225

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>

Upvotes: 1

Try this

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


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

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

Upvotes: 1

swapnesh
swapnesh

Reputation: 26732

Change

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

To

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

Add an event handler if you want to do it via button click.

Upvotes: 1

Related Questions