I'm going to write a page the allow user click the checkbox of the item and then calculate the total amount of it
But I found that I can't get the element from checked check box. How do i return the value of that checkbox
Here is my code :
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>
Your form's name attribute is missing.
define like this one
<form action="" id="listForm" name="listForm" >
define JS:
function calculate() {
if (document.forms["listForm"]["item1"].checked == true)
prize1 = document.forms["listForm"]["item1Q"].value * document.forms["listForm"]["item1"].value
total = prize1
alert("The total is " + total)
}
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>
Using jQuery instead of Javascript would make code more readable and manageable. If this is feasible for you please try below code:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.