我要写一个页面,允许用户点击该项目的复选框,然后计算它的总金额
但我发现我无法从勾选复选框中获取该元素。如何返回该复选框的值
这是我的代码:
function calculate(){
if(document.forms["listForm"].getElementsByTagName("item1").checked==true)
prize1 = document.forms["listForm"].getElementsByTagName("item1Q").value * document.forms["listForm"].getElementsByTagName("item1").value
total = prize1
alert("The total is "+total)
}
<form action="" id="listForm" >
<table border="1" >
<tr>
<td style="text-align: center; width: 500px"><b>Books</b></td>
<td style="text-align: center; width: 50px"><b>Quantity</b></td>
</tr>
<tr>
<td><input type="checkbox" name="item1" value="19.95" />
XHTML Basic, $19.95</td>
<td><input type="text" name="item1Q" value="0" size="2" maxlength="2" /></td>
答案 0 :(得分:1)
您的表单名称属性丢失。
像这样定义
while read line
do
$(/usr/bin/xyz argument1 argument2)
echo '$line'
done <<<
定义JS:
<form action="" id="listForm" name="listForm" >
答案 1 :(得分:0)
function calculate(){
if(document.forms["listForm"]["item1"].checked=true)
var prize1 = Number(document.forms["listForm"]["item1Q"].value) * Number(document.forms["listForm"] ["item1"].value)
var total = prize1;
alert("The total is "+total);
}
<form action="" id="listForm" >
<table border="1" >
<tr>
<td style="text-align: center; width: 500px"><b>Books</b></td>
<td style="text-align: center; width: 50px"><b>Quantity</b></td>
</tr>
<tr>
<td><input type="checkbox" name="item1" value="19.95" onchange="calculate()"/>
XHTML Basic, $19.95</td>
<td><input type="text" name="item1Q" value="2" size="2" maxlength="2" /> </td>
答案 2 :(得分:0)
使用jQuery而不是Javascript会使代码更具可读性和可管理性。如果这对您来说可行,请尝试以下代码:
https://jsfiddle.net/6q3o6ghn/
<script>
$(document).ready(function(){
$('input[name=item1]').on('change',function(){
if($(this).is(':checked') == true) {
calculate($(this).val());
}
});
});
function calculate(_value) {
prize1 = $('input[name=item1Q]').val() * _value;
total = prize1
alert("The total is " + total)
}
</script>
<form action="" name="listForm" id="listForm" >
<table border="1" >
<tr>
<td style="text-align: center; width: 500px"><b>Books</b></td>
<td style="text-align: center; width: 50px"><b>Quantity</b></td>
</tr>
<tr>
<td><input type="checkbox" name="item1" value="19.95"/>
XHTML Basic, $19.95</td>
<td><input type="text" name="item1Q" value="0" size="2" maxlength="2" /></td></tr>