可以通过ClassName

时间:2015-12-01 04:19:13

标签: javascript

这里是否可以使用getElementByClassName获取值,我应该在parseFloat中为sum部分添加什么?

这里的想法是从每个复选框中获取总金额并计算总数。

我不能使用外部库,所以这里只有纯javascript选择器,我不能在while echo语句中更改任何内容。

<?php
include_once('database_conn.php');
$sqlCDs = 'SELECT CDID, CDTitle, CDYear, catDesc, CDPrice FROM nmc_cd b inner join nmc_category c on b.catID = c.catID WHERE 1 order by CDTitle';
$rsCDs = mysqli_query($conn, $sqlCDs);
while ($CD = mysqli_fetch_assoc($rsCDs)) {
    echo "\t<div class='item'>
            <span class='CDTitle'>{$CD['CDTitle']}</span>
            <span class='CDYear'>{$CD['CDYear']}</span>
            <span class='catDesc'>{$CD['catDesc']}</span>
            <span class='CDPrice'>{$CD['CDPrice']}</span>
            <span class='chosen'><input type='checkbox' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
        </div>\n";
}
?>

<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
            <input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>

JS:

function isChecked(chosen) {
var number = parseFloat(document.getElementsByClassName('CDPrice')[0].innerHTML);
    if(chosen.is(':checked')) {
        sum = sum + parseFloat(????);
    } else {
        sum = sum - parseFloat(????);
    }
    $('#total').???('CDPrice')[0].innerHTML(sum.toFixed(2));
}

1 个答案:

答案 0 :(得分:1)

这是一个纯JavaScript的解决方案。复选框事件处理程序在HTML中是硬编码的,这不是最佳实践,但它只是向您展示如何使其工作的简单方法。

function isChecked() {
  var sum = 0; //store a running sum
  
  //find all price elements: class "CDPrice" within element of class "item"
  [].forEach.call(document.querySelectorAll(".item .CDPrice"), function(item) {
    //get the corresponding checkbox
    var chosen = item.parentElement.querySelector('[type="checkbox"]');
    
    //if checked, add to the running sum
    if (chosen.checked) {
      var value = parseFloat(item.innerHTML) || 0; //if parseFloat() returns NaN, default value to zero
      sum += value;
    }
  });
  
  //update the total
  var total = document.getElementById("total");
  total.value = sum.toFixed(2);
}
<div class='item'>
  <span class='CDTitle'>Title1</span>
  <span class='CDYear'>Year1</span>
  <span class='catDesc'>Description1</span>
  <span class='CDPrice'>12.34</span>
  <input type='checkbox' onchange="isChecked();" />
</div>
<div class='item'>
  <span class='CDTitle'>Title2</span>
  <span class='CDYear'>Year2</span>
  <span class='catDesc'>Description2</span>
  <span class='CDPrice'>56.78</span>
  <input type='checkbox' onchange="isChecked();" />
</div>
<div class='item'>
  <span class='CDTitle'>Title3</span>
  <span class='CDYear'>Year3</span>
  <span class='catDesc'>Description3</span>
  <span class='CDPrice'>(None)</span>
  <input type='checkbox' onchange="isChecked();" />
</div>

<input id="total" />