dream2891 2013-03-16 12:49
浏览 90
已采纳

3个具有相同名称和相同数值的复选框

Given this code:

<input type="checkbox" id="Coke" name="Price" value="70" />
<input type="checkbox" id="Fanta" name="Price" value="70" />
<input type="checkbox" id="Sprite" name="Price" value="70" />

I would like to know how, if my user selects Fanta checkbox, I want my php variable $type="Fanta" but I need form checkbox VALUES to stay NUMERIC for total price calculation.

  • 写回答

4条回答 默认 最新

  • doumuyu0837 2013-03-16 12:57
    关注

    It's not clear what exactly you're asking, but I believe you basically want 2 fields, one that defines the price and one that defines the selected type.

    In that case, your best bet would be to store the prices server-side (That way people can't modify them too, which is good!). If you do this, your checkboxes will look like this:

    <input type="checkbox" id="Coke" name="type[]" value="Coke" />
    <input type="checkbox" id="Fanta" name="type[]" value="Fanta" />
    <input type="checkbox" id="Sprite" name="type[]" value="Sprite" />
    

    Your backend code would look like this:

     $prices = array(
         'Coke' => 70,
         'Fanta' => 70,
         'Sprite' => 70
     );
    
     $types = $_POST['type'];
     $total = 0;
    
     foreach($types as $key => $type) {
         if (!isset($prices[$type]))
             continue;
    
         $total += $prices[$type];
     }
    
     // Use $total as your total price for whatever calculation
     echo $total;
    

    As per your comment, if you still want these prices client side for calculations, you can use json_encode to output it into a script tag and use the prices directly. It's basically going to turn the server-side prices array into a client-side array of prices.

    <script type="text/javascript">
        var prices = <?= json_encode($prices) ?>;
    
        // Now you can use prices['Coke'] etc, based off the value of the selected checkbox.
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法