从多个复选框和单选按钮获取信息

时间:2013-05-17 09:11:43

标签: javascript html checkbox

我正在一个网站上订购汉堡,并希望人们使用单选按钮挑选一个汉堡,然后让他们使用一系列复选框选择额外的浇头。我可以单独使用单选按钮,现在正在添加复选框。我目前的HTML是

<td style="border:5px solid #39973B" colspan=2>
     <input id="size" name="beef" data-price="6.00" value="1" type="radio">single &pound6.00
     <input id="size" name="beef" data-price="7.00" value="2" type="radio">double &pound7.00
     </td>
<tr >
<td style="border:5px solid #39973B" colspan=2 >
<table>
<td align="center" colspan=5 style="border:2px solid #39973B"> Additional toppings (50p per topping)</td><br>
                      </tr><td style="padding:6px">Cheese</td><td style="padding:6px">Bacon</td><td style="padding:6px">Onions</td>
              </tr>

              <tr style="border:2px solid #39973B" ><td>
                  <input type="checkbox" name="Topping" value="Cheese"></td><td>
                  <input type="checkbox" name="Topping" value="Bacon"></td><td>
                  <input type="checkbox" name="Topping" value="Onions"></td>
                  </table>
                  <input id="addbeef" name="beef" type="button"  value="add">
                  </td>
                  </tr>
</table>

我已经定义了我的浇头及其成本

var top =["Cheese" , "Bacon", "Onions"];
  var cost=[.50, .50, .50];

我的javascript是

function getCheckedBoxes() {
    var css = 'input#size[name="beef"]:checked';
    var input = document.querySelector(css);    
    var size = input.value==='1'?'single':'double';
    var price = Number(input.getAttribute('data-price'));
  var checkboxes = document.getElementByName("Topping");
  var checkboxesChecked = [];
  for (var i=0; i<checkboxes.length; i++) {
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
    for (var j=0; j<checkboxesChecked.length; j++){
        size+=top[j];
        price+=cost[j];
    }
    var orderline = [this.name,size,price];
    addToBasket(orderline);
}

非常感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:0)

var checkboxes = document.getElementByName("Topping");
for (var val,i=0; i<checkboxes.length; i++) {
   if (checkboxes[i].checked) {
      val = checkboxes[i].value;
      size+=top[val]+" ";
      price+=cost[val];
   }
}