简体   繁体   中英

PHP Make a simple calculator - Code doesnt work

I am trying to make a simple calculator like this :

input1 select input2 = input3

  • input1,input2 is first and second value
  • select have 4 operator : + - * /
  • input3 show the result

This is my code and it doesnt work as expected,can someone help me out ?

<?php
ini_set('display_errors', 0);
session_start();

/*  Check if form is submit 
 *  if any input field is empty --> "NaN" result
 *  else check value of select field --> do the math --> result
 *  Then call JS function to change value of result field
 */ 

if(isset($_GET['act']) && $_GET['act']== 'do')  {

    $val1 = $_GET['val1'];
    $val2 = $_GET['val2'];
    $oper = $_GET['oper'];
if($val1 == NULL || $val2 == NULL)  
    $result= "NaN";
else    {
    switch($oper)   {
        case 1 : $result= $val1 + $val2; break;
        case 2 : $result= $va1l - $val2; break;
        case 3 : $result= $val1 * $val2; break;
        case 4 : $result= $val1 / $val2; break;
    }
}
echo "<script> showResult('".$result."') </script>";
}
?>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
input,select { height:30px;width:50px}

</style>



</head>
<body>
<form method="GET" action="bai4_1.php?act=do">
    <table>
    <tr><td>Op1</td>
        <td>Oper</td>
        <td>Op2</td>
        <td>Result</td></tr>
    <tr><td><input id="val1" type="text" name="val1" value="<?php echo 
$_GET['val1'];?>"/></td>
        <td><select id="oper" name="oper">
            <option value=1>+</option>
            <option value=2>-</option>
            <option value=3>*</option>
            <option value=4>/</option>
            </select></td>
        <td><input id="val2" type="text" name="val2" value="<?php 
echo$_GET['val2'];?>"/> =</td>         
        <td><input id="result" type="text"></td></tr>
    </table>
</form>
</body>
</html>


<script>
$("input,select").change(function(){
setTimeout(function(){
    $("form").submit();
},1000);
});

function showResult(result) {
$("#result").val(result);
}   
</script>

First know what languages you want to use for you application.

I see you use PHP, HTML, JavaScript and jQuery.

But if you rethink your small application, you will (maybe) notice that you can do all your actions client side. So you could trow away your PHP.

So now we need HTML to display a form.

<form>
    <table>
        <tr>
            <td>Op1</td>
            <td>Oper</td>
            <td>Op2</td>
            <td>Result</td>
        </tr>
        <tr>
            <td>
                <input id="val1" type="text" name="val1" value="" />
            </td>
            <td>
                <select id="oper" name="oper">
                    <option value="+">+</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    <option value="/">/</option>
                </select>
            </td>
            <td>
                <input id="val2" type="text" name="val2" value="" />
            </td>
            <td>
                <input id="result" type="text" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td>
                <input type="submit" />
            </td>
        </tr>
    </table>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

In your HTML I edited some things:

  • I added an input type="submit" , we can't assume the user is able to send the form without.
  • Also I change the values of your select box

Now the form is ready.

With a little knowledge about jQuery we can easily catch the submit event.

$('form').submit(onFormSubmit)

function onFormSubmit() {
    var val1 = $('#val1').val()
    var val2 = $('#val2').val()
    var operator = $('#oper').val()

    $('#result').val(eval(val1 + operator + val2))
    return false
}

Explained above, I have an event listener on the from.

After submit I get the 3 values.

I use eval to use strings as code, that way I can do eval(val1 + operator + val2)

I hope this will help you.

Include a jsFiddle example here .

You are probably getting a JavaScript error when you load your page. Currently, the source code output of your page probably looks like this:

<script> showResult('".$result."') </script>
<html>
...
</html>
<script>
...
function showResult(result) {
$("#result").val(result);
}   
</script>

There are two problems here:

You shouldn't have anything, even <script> , outside of your <html> tags.

You can move this stuff into the <head> tags so make it look and work nicer. It's considered bad practice to put things outside of the <html> tags.

You are calling your JavaScript function before you define it.

The first JavaScript line tries to execute your ShowResult function. However, this hasn't been defined yet (it's defined at the bottom of the page, and JavaScript hasn't read it yet), so it doesn't know what to do. This causes an error. If you are using Google Chrome or Firefox, then you can view this error message by hitting Control-Shift-J.

The Fix

First, move all of your JavaScript code into the <head> of your page.

Second, write your functions first. This will define them as the page loads, so everything is available once you start executing functions.

Third, when you use jQuery, wrap your function execution code (ie: showResult('".$result."') ) in this code:

$(document).ready(function() {
    // put your code here
});

This will instruct your code to wait for the entire page to load before starting to execute any JavaScript.

The result should look something like this:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
//  define your functions up here
function showResult(result) {
    $("#result").val(result);
}  

//  define your Procedural code here. This stuff will execute once the page loads completely:
$(document).ready(function() {
    $("input,select").change(function(){
    setTimeout(function(){
        $("form").submit();
    },1000);
    });

    <?php if($result != "NaN") {
    //  Show this code only if $result is defined and valid:
echo "showResult('".$result."');";
?>
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM