[英]Javascript function not accessing a check boxes checked value by document.getElementById
Javascript is not my strong point and I'm trying to write a simple function to count how many checkboxes are selected by the user. Javascript不是我的强项,我正在尝试编写一个简单的函数来计算用户选中了多少个复选框。 These checkboxes are generated from values stored a database and represent a choice of toppings available for a customer ordering pizza.
这些复选框是从存储在数据库中的值生成的,表示可供客户订购披萨的浇头选择。
Javascript: Javascript:
<script type="text/javascript">
function countBoxes()
{
var aCounter = 0;
var count = 0;
while (count < 10){
var aString = 'topping' + count;
var aCheckbox = document.getElementById(aString);
if (aCheckbox.checked)
{
aCounter++;
}
count++;
}
alert(aCounter + 'boxes have been ticked');
}
</script>
PHP: PHP:
echo "<table>";
while($row = mysql_fetch_assoc($product))
{
echo "<tr><td>".$row['topping_name']."</td><td>".price($row[$aString])."</td><td> <input type=\"checkbox\" id=\"topping".$counter."\" name=\"topping".$counter."\" value=\"".$row['topping_name']."\" onclick=\"countBoxes()\"\" ></td></tr>";
$counter + 1;
}
echo "</table>";
For some reason the 'checked' state of the check box is not being picked up? 由于某种原因,未选中复选框的“已选中”状态? Does anyone know why this is?
有人知道为什么是这样吗?
Generated HTML 生成的HTML
<table><tr><td>Pepperoni</td><td>0.00</td><td><input type="checkbox" id="topping" name="topping" value="Pepperoni" onclick="countBoxes()"" ></td></tr><tr><td>Ham</td> <td>0.00</td><td><input type="checkbox" id="topping" name="topping" value="Ham" onclick="countBoxes()"" ></td></tr><tr><td>Sausage</td><td>0.00</td><td><input type="checkbox" id="topping" name="topping" value="Sausage" onclick="countBoxes()"" ></td></tr><tr><td>Red Onions</td><td>0.00</td><td><input type="checkbox" id="topping" name="topping" value="Red Onions" onclick="countBoxes()"" ></td></tr></td></tr></table>
The problem it's when you write 问题是你写的时候
if (aCheckbox.checked)
because if your aCheckbox = null, you have an error on aCheckbox.checked 因为如果您的aCheckbox = null,则您在aCheckbox.checked上有一个错误
if ( aCheckbox && aCheckbox.checked)
the jsFiddle can help you jsFiddle可以帮助您
replace 更换
onclick="countBoxes();"
by 通过
onchange="countBoxes();"
and change the javascript function by 并通过更改JavaScript函数
function countBoxes()
{
var aCounter = 0;
var count = 0;
var element = null;
while (element = document.getElementById('topping' + count)){
if (element.checked)
aCounter++;
count++;
}
alert(aCounter + 'boxes have been ticked');
}
Fiddle: http://jsbin.com/oWAcegE/2/ 小提琴: http : //jsbin.com/oWAcegE/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.