fifamaniac04
fifamaniac04

Reputation: 2383

How to populate input fields with PHP

I'm trying to write a simple calculator html page where I ask for two numbers in separate text boxes, have the user click a button and then the result gets stored into a third text box. I'm trying to using PHP to resolve this but can't seem to display it the way I want. the echo line works fine, but I don't want that;

From HTML

     <form action="Add.php" method="get">
        <input for='num1' type="text"  name="num1" />
        <input for='num2' type="text" name="num2" />

        <input type="submit" value="Add Them" />
        <input type="text" name="AnswerBx" id="SumTotalTxtBx"/>
    </form> 

Add.php

     <?php 
        $num1 = $_GET["num1"];
        $num2 = $_GET['num2'];
        $sum = $num1+$num2;
        //echo "$num1 + $num2 = $sum";

        document.getElementById("SumTotalTxtBx").value = $sum;
    ?>

Upvotes: 1

Views: 25053

Answers (4)

Arcym
Arcym

Reputation: 490

Okay, so PHP is awesomeness, but all of it's calculations are performed on the serverside, not the clientside. Using AJAX, you can execute some of the PHP code back against the server, but I think you may be more interested in javascript for your calculator.

<html>
<head>
<script>
function calculateSum()
{
    num1 = parseInt(document.getElementById("num1").value);
    num2 = parseInt(document.getElementById("num2").value);

    sum = num1 + num2;

    document.getElementById("sum").innerHTML = sum;
}
</script>
<body>
<input id="num1" type="text"/><br/>
<input id="num2" type="text"/><br/>
<button onclick="calculateSum()">Submit!</button>
<span id="sum">..the sum is..</div>
</body>
</html>

Javascript is really quite simple, and is absolutely wonderful when programming anything on the clientside. If you want to learn more, I'd suggest you read up on javascript over at w3schools! I hope that helps!!

Upvotes: 0

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

Using jQuery you can solve it without doing post back's at Server like this

var num1 = parseInt($("input:text[name='num1']"));
var num2 = parseInt($("input:text[name='num2']"));
$('input:text#SumTotalTxtBx').val(num1+num2);

Upvotes: 0

sachleen
sachleen

Reputation: 31131

You can't mix PHP and JavaScript like that! One is run on the server the other on the client.

You have to echo the value into the value attribute of the text boxes like so

<input type="text" value="<?PHP echo $sum; ?>" />

Upvotes: 8

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

You are mixing PHP and Javascript here, go back to the PHP manual at : http://php.net/manual and read out how php works and interacts with the user.

Javascript is basicaly run on the client side while PHP is run on the server. You REQUEST php something and it returns a new HTML page for you.

That being said, its a too broad topic to help you fix your error.

Good luck

Upvotes: 0

Related Questions