【问题标题】:How to update the sum of selected option elements on change如何在更改时更新所选选项元素的总和
【发布时间】:2018-06-20 21:42:46
【问题描述】:

我试图了解为什么总和没有更新。

这是我的下拉列表:

echo "<select name='CPU'>";
while ($row = mysqli_fetch_array($result)) {
    if($row['id']==1)
        echo "<option value='" . $row['id'] . "'a='" . $row['productprice'] 
       . "'>" . $row['productname'] . "</option>";
    else if($row['productstock']>0 && $row['id']>1)
        echo "<option value='" . $row['id'] . "'a='" . $row['productprice'] 
       . "' >" . $row['productname'] . " Price:" . $row['productprice'] . "</option>";
}
echo "</select>";

这是我更新总和的函数:

$('select').change(function(){
    var sum = 0;
    $('select :selected').each(function() {
        sum += Number($(this).attr("a"));
    });
    $("#sum").html(sum);
    //
});

【问题讨论】:

  • 更新函数好像是javascript,不是php。
  • 这个$('select :selected') 不会选择选项
  • 总和是什么?可以选择多个“CPU”还是有其他select
  • 我还有 9 个其他选择与此处的选择类似。

标签: php jquery html select onchange


【解决方案1】:

每次调用

$('select').change(function(){

您正在再次初始化var sum = 0;,这就是它没有被添加到先前值的原因。只需在页面加载时取出初始化并初始化一次。

$(document).ready(function(){
   var sum = 0;
   $('select').change(function(){
      $('select :selected').each(function() {
         sum += Number($(this).attr("a"));
      });
   $("#sum").html(sum);
   })
});

>>>Demo<<<

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多