根据一系列单选按钮对的状态进行计算的好方法是什么?

时间:2019-04-22 21:12:48

标签: javascript

我有一个表,其中包含未知数目的行,每个表都有两个单选按钮,分别名为weight [i]和Winner [i],并带有ID,例如weight11,weight12,weight21,weight22,winner11,winner12等。 ..

我正在尝试创建一个循环,以计算所有这些单选按钮的值的乘积之和。

单选按钮的名称包含一个变量时,我无法编写正确的查询来获取单选按钮的值。

您能看到正确的查询是什么,还是可以找到其他解决方案?

我尝试使用php进行循环,但是我无法获取php中的行数值,因为它可以动态更改而无需重新加载表。

表格:

<table class="comparisontable" id="ComparisonTable">
    <col width=15%>
    <col width=15%>
    <col width=20%>
    <col width=5%>
    <col width=20%>
    <col width=25%>
    <tr>
        <th class="headingleft">Criteria</th>
        <th class="headingcenter">Criteria weight</th>
        <th class="headingcenter"><p><p><input onClick="this.setSelectionRange(0, this.value.length)" onMouseOver="this.style.cursor='pointer'" class="productchoice" type="text" id="productA" name="productA" value = "<?php echo $array[0]["ProductA"];?>"></p><p id=prodscoreA>Score: </p></th> 
        <th class="headingcenter">
        <th class="headingcenter"><p><p><input onClick="this.setSelectionRange(0, this.value.length)" onMouseOver="this.style.cursor='pointer'" class="productchoice" type="text" id="productB" name="productB" value = "<?php echo $array[0]["ProductB"];?>"></p><p id=prodscoreB>Score: </p></th>
        <th class="headingleft">Comment</th>
    </tr>


<!-- Criteria rows creation and loading, in a loop: -->
    <?php
        $i = 1; 
        while($array[$i-1]["FormNumber"]) {
    ?>

    <tr>
        <td class="criteria"><input onClick="this.setSelectionRange(0, this.value.length)" onMouseOver="this.style.cursor='pointer'" class="criteriainput" type="text" id="criteria<?php echo "$i";?>" name="criteria[<?php echo "$i";?>]" value="<?php echo $array[$i-1]["Criteria"];?>"></td>
        <td class="weight">
            <li class="star-weight">
                <input type="radio" onclick="CalculateScores()" name="weight[<?php echo "$i";?>]" id="weight<?php echo "$i";?>3" value="3" <?= $array[$i-1]["Weight"] == "3" ? 'checked' : '' ?> /><label for="weight<?php echo "$i";?>3"></label>
                <input type="radio" onclick="CalculateScores()" name="weight[<?php echo "$i";?>]" id="weight<?php echo "$i";?>2" value="2" <?= $array[$i-1]["Weight"] == "2" ? 'checked' : '' ?> /><label for="weight<?php echo "$i";?>2"></label>
                <input type="radio" onclick="CalculateScores()" name="weight[<?php echo "$i";?>]" id="weight<?php echo "$i";?>1" value="1" <?= $array[$i-1]["Weight"] == "1" ? 'checked' : '' ?> /><label for="weight<?php echo "$i";?>1"></label>
            </li>
        </td>
        <td class="winner">
            <input type="radio" onclick="CalculateScores()" name="winner[<?php echo "$i";?>]" id="winner<?php echo "$i";?>10000" value="10000" <?= $array[$i-1]["Winner"] == "10000" ? 'checked' : '' ?>> Winner</input><br>
            <textarea class="commentinput" name="commentA[<?php echo "$i";?>]" id="commentA<?php echo "$i";?>" cols="1" rows="3"><?php echo $array[$i-1]["CommentA"];?></textarea>
        </td>
        <td>
            <input type="radio" onclick="CalculateScores()" name="winner[<?php echo "$i";?>]" id="winner<?php echo "$i";?>100" value="100" <?= $array[$i-1]["Winner"] == "100" ? 'checked' : '' ?>> Tie</input><br>
            <input class="hidden" type="radio" name="winner<?php echo "$i";?>" id="winner<?php echo "$i";?>0" value="0" <?= $array[$i-1]["Winner"] == NULL ? 'checked' : '' ?>><br>
        </td>
        <td class="winner">
            <input type="radio" onclick="CalculateScores()" name="winner[<?php echo "$i";?>]" id="winner<?php echo "$i";?>1" value="1" <?= $array[$i-1]["Winner"] == "1" ? 'checked' : '' ?>> Winner</input><br>
            <textarea class="commentinput" name="commentB[<?php echo "$i";?>]" id="commentB<?php echo "$i";?>" cols="1" rows="3"><?php echo $array[$i-1]["CommentB"];?></textarea>
        </td>
        <td class="comment">
            <textarea class="commentinput" name="comment[<?php echo "$i" ;?>]" id="comment<?php echo "$i" ;?>" cols="1" rows="4"><?php echo $array[$i-1]["Comment"];?></textarea>
        </td>
    </tr>

    <?php
            $i++;
        }
    ?>

</table>

JavaScript函数:

function CalculateScores() {
    // Sum of product of weights and winners:
    var SumProd = 0;
    var l = 1;
    var rows = document.getElementById("ComparisonTable").rows.length;
    while(l < rows) {
        SumProd += document.querySelector('input[name="weight[" + l + "]"]:checked').value*document.querySelector('input[name="winner[" + l + "]"]:checked').value;
        l++;
    }

我希望SumProd等于所检查的权重[l]和获胜者[l]单选按钮的乘积之和。

1 个答案:

答案 0 :(得分:0)

内联查看注释,但不要忘记,对于每组单选按钮,您应该使用唯一的name属性值,并且需要使用直引号而不是智能引号。

// Get all the rows into an array:
let rows = Array.prototype.slice.call(document.querySelectorAll("tr"));

let sum = 0;

document.querySelector("button").addEventListener("click", function(){

  // Loop over the array
  rows.forEach(function(row){
    // Get the selected radio button
    let checkedButton = row.querySelector(":checked");
    
    // If a selection was made, add the value (converted to a number) of the checked radio button to the sum
    if(checkedButton !== null){
      sum += +checkedButton.value;
    }
  });

  console.log(sum);  // Output result
});
<table>
  <tr>
    <td>Choice 1:<input type="radio" value="5" name="g1"> Choice 2:<input type="radio" value="10" name="g1"></td>
  </tr>
  <tr>
    <td>Choice 1:<input type="radio" value="15" name="g2"> Choice 2:<input type="radio" value="20" name="g2"></td>
  </tr>
  <tr>
    <td>Choice 1:<input type="radio" value="25" name="g3"> Choice 2:<input type="radio" value="30" name="g3"></td>
  </tr>
  <tr>
    <td>Choice 1:<input type="radio" value="35" name="g4"> Choice 2:<input type="radio" value="40" name="g4"></td>
  </tr>
  <tr>
    <td>Choice 1:<input type="radio" value="45" name="g5"> Choice 2:<input type="radio" value="50" name="g5"></td>
  </tr>
</table>

<button>Get Sum</button>

更新:

对于您的情况,在循环内,您只需要获取检查的权重和检查的获胜者单选按钮值,将它们相乘,然后将结果加到最终总和即可:

  // Loop over the array
  rows.forEach(function(row){
    // Get the selected radio buttons
    let weight = row.querySelector("[name^='weight']:checked");
    let winner = row.querySelector("[name^='winner']:checked");

    // If a selection was made, multiply the values (converted to a number) 
    // of the checked radio buttons and add to the sum
    if(weight && winner){
      sum += (+weight.value * +winner.value);
    }
  });