开发者

Simple PHP Budget [closed]

开发者_运维百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I'm trying to make a simple budget form. What I need is that if some item is checked the system adds the price of these item (and if unchecked that item again substract it's price of the total).

<form name="myform" method ='post'>
<input name="item" type="checkbox" value="flowers"/>
<input name="item" type="checkbox" value="animals"/>
</form>

And what I want is something like

if (item[1].checked) $total_price = $total_price + item[1];

And likewise

if (item[1].unchecked) $total_price = $total_price - item[1];


Here is a quick example of how you might implement the above. I have not tested it, but it is something to get started with.

<?php

$price_list = array(
    'animals' => 100,
    'flowers' => 50
);

// Has data from form been posted back?
if (!empty($_POST)) {
    $total_price = 0;

    foreach ($_POST['item'] as $item) {
        // Is price available for item?
        if (isset($price_list[ $item ]))
            $total_price += $price_list[ $item ];
        else
            throw new Exception('Invalid item: ' . $item);
    }

    echo 'Total Price: ', $total_price;

    // End script before form is shown again.
    die;
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Item Counter</title>
</head>
<body>
    <form action="" method="post">
        <input id="itemFlowers" name="item[]" type="checkbox" value="flowers"/>
        <label for="itemFlowers">Flowers $<?php echo $price_list['flowers']; ?></label>
        <input id="itemAnimals" name="item[]" type="checkbox" value="animals"/>
        <label for="itemAnimals">Animals $<?php echo $price_list['animals']; ?></label>

        <input name="submit" type="submit" value="Submit" />
    </form>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜