Question

I'm trying to calculate factorial of a number in PHP. I've got two text boxes: 1) for number 2)for result(the factorial of the number)

When I click submit, I want the result in the textbox of result.How can I make it happen.

<html>
    <title>Factorial</title>
    <body>
    <form name="f1" method="POST">
    number :<input type="text" name="T1">
    factorial :<input type="text" name="T2" >
    <input type="submit" name="submit">
</body>
</html> 

<?php
if(isset($_POST['submit']))
{
 $num=$_POST['T1'];
 $fact=1;

 while($num>0)
 {
  $fact=$fact*$num;
   $num--;
  }

  //code for writing result to the textbox.

  }
  ?>
Was it helpful?

Solution

Try this:

<?php
if(isset($_POST['submit']))
{
 $num=$_POST['T1'];
 $fact=1;

 while($num>0)
 {
  $fact=$fact*$num;
   $num--;
 }

//code for writing result to the textbox.

 }
?>


<html>
<title>Factorial</title>
<body>
<form name="f1" method="POST">
number :<input type="text" name="T1" value="<?php isset($num) ? $num : ''?>">
factorial :<input type="text" name="T2" value="<?php isset($fact)? $fact : '';?>">
<input type="submit" name="submit">
</body>
</html>

OTHER TIPS

Do your PHP before the HTML, and then when you get to wherever you want to show it on the page, just add <?php echo $fact; ?>

So maybe something like

<div>
<?php echo $fact; ?>
</div>

Note value="<?php echo $fact; ?>" in factorial input

<?php
$fact ='';
if(isset($_POST['submit']))
{
 $num=$_POST['T1'];
 $fact=1;

 while($num>0)
 {
  $fact=$fact*$num;
   $num--;
  }

  }
  ?>
<html>
    <title>Factorial</title>
    <body>
    <form name="f1" method="POST">
    number :<input type="text" name="T1">
    factorial :<input type="text" name="T2" value="<?php echo $fact; ?>" >
    <input type="submit" name="submit">
</body>
</html> 

try like this using jQuery call a method to do ur action

         function fact(){
         //do calculation
          $('#id_of_txt_box').val('the value');
          }

You can try out similar thing for javascript

You just have to add script tag after calculating factorial

Try this :

echo '<script type="text/javascript">
var s = document.getElementById("t2");
        s.value = ' . $fact . ';
</script>';

"t2" is the id of the input element where you wish to put the calculated value.

add this code after calculating factorial within php tags

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top