Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting button value on click and echo it

Tags:

php

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"];
}
?>
like image 499
user2500189 Avatar asked Jun 19 '13 08:06

user2500189


3 Answers

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"];
   }
?>
like image 158
MrCode Avatar answered Oct 15 '22 13:10

MrCode


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.

like image 1
swapnesh Avatar answered Oct 15 '22 12:10

swapnesh


Try this

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


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

        echo $_POST["zero"];
    }
    ?>
like image 1
Subhra Sekhar Mukhopadhyay Avatar answered Oct 15 '22 11:10

Subhra Sekhar Mukhopadhyay