dimanche 1 août 2021

Calculating value of checkboxes with JavaScript

I need to calculate the values of items in an HTML form using checkboxes. Each checkbox is related to a product serial number, and each checkbox in the form has a different points value. I can't allow the sum of the values to be greater than a predetermined number. I found this JavaScript, which calculates the sum, but when I use it in a form, I can't parse the actual item number. Instead, the form returns the value of a checkbox.

Here is the JavaScript:

<script type="text/javascript"> 
function chkcontrol(j) {
var sum=0;
for(var i=0; i < document.form1.ckb.length; i++){

if(document.form1.ckb[i].checked){
sum = sum + parseInt(document.form1.ckb[i].value);
}
document.getElementById("msg").innerHTML="Sum :"+ sum;

if(sum >500){
sum = sum - parseInt(document.form1.ckb[j].value);
document.form1.ckb[j].checked = false ;
alert("Sum of the selection can't be more than 500") 
//return false;
}
document.getElementById("msg").innerHTML="Sum :"+ sum;
}
}
</script>

And the table looks like this:

<form name=form1 method=post action=check.php>

<table class='table table-striped'>
  
<tr><th>Select</th></tr>
<tr><td><input type=checkbox name=ckb value=120 onclick='chkcontrol(0)';> Serial# 123001 (value = 120) </td></tr>
<tr><td><input type=checkbox name=ckb value=200 onclick='chkcontrol(1)';> Serial# 123002 - (value = 200) </td></tr>
<tr><td><input type=checkbox name=ckb value=350 onclick='chkcontrol(2)';> Serial# 123003 - (value = 350) </td></tr>
<tr><td><input type=checkbox name=ckb value=100 onclick='chkcontrol(3)';> Serial# 123004 - (value = 100) </td></tr>
</table></form>
Sum of the values can't exceed 500. 
<br><br>
<div id=msg></div>

Currently, the value of the checkbox is the number that is added to the sum. When I parse the form, I can only get that number via the name cab and I don't get any information about the Serial#. What I need is to be able to have the value of the checkbox be equal to a serial number of the item - i.e. 123004 - and I can later reference this serial number in a database.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire