使用PHP和HTML计算两本书的总价

时间:2015-07-07 18:55:17

标签: php

我想知道使用php和html的方式是什么,以便我提供书籍下拉菜单,我需要从该下拉列表中选择两个选项,然后计算两本书的价格总和。 / p>

假设我已经硬编码书籍说:

Book 1 - $5
Book 2 - $15
Book 3 - $50

我知道如果只选择一本书。但不知道这个。请帮忙

代码:

<?php
if(isset($_POST['formSubmit'])) 
{
    $varCurrentBook = $_POST['formBook'];
    $errorMessage = "";

    if(empty($varCurrentBook)) 
    {
        $errorMessage = "<li>You forgot to select a Book!</li>";
    }

    if($errorMessage != "") 
    {
        echo("<p>There was an error with your form:</p>\n");
        echo("<ul>" . $errorMessage . "</ul>\n");
    } 
    else 
    {
        switch($varCurrentBook)
        {
            //Can use here to find what option is clicked
        }
        exit();
    }
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    <label for='formBook'>Select a Book</label><br>
    <select name="formBook">
        <option value="0">Select a Book...</option>
        <option value="15">The Secret</option>
        <option value="10">The Fairy Tales</option>
        <option value="5">All about words</option>
        <option value="100">Pinaacle Studio</option>
        <option value="120">Harry Potter</option>
        <option value="200">Thinking in Java</option>
   </select> 
   <input type="submit" name="formSubmit" value="Submit" />
</form>

3 个答案:

答案 0 :(得分:0)

您需要使用多重选择:

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for='formBook'>Select a Book</label><br>
<select name="formBook[]" multiple><!--The multiple attribute-->
    <option value="0">Select a Book...</option>
    <option value="15">The Secret</option>
    <option value="10">The Fairy Tales</option>
    <option value="5">All about words</option>
    <option value="100">Pinaacle Studio</option>
    <option value="120">Harry Potter</option>
    <option value="200">Thinking in Java</option>
</select> 
<input type="submit" name="formSubmit" value="Submit" />
</form>

另请注意我如何将名称从formBook更改为formBook[]。这会将$_POST['formBook']更改为一系列选项。

然后您可以按以下方式访问它:

<?php
  foreach ($_POST['formBook'] as $names)
  {
    print "You have selected $names<br/>";
    /*Your also need to change your code here accordingly.*/
  }

?>

答案 1 :(得分:0)

当ARBY回答正确时,您必须将multiple属性添加到select元素中:

<select name="formBook" multiple>

这会发送value属性。 (例如0/15/10)

所以你可以检查一下你是否有两本这样的书:

//Check if the user has selected exactly two books
$formBooks = $_POST['formBook'];
if(count($formBooks) !== 2){
    //TODO: return error message that user has to select two books
}

//Calculate the value
$result = array_sum($formBooks);

//TODO: return value

答案 2 :(得分:0)

你必须使用多个select和jquery 见:HTML Multiselect Limit

{{1}}

然后你可以总结所有选定的元素

{{1}}