Calculating value of checkboxes with JavaScript - 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.

You can create a data attribute for each of the checkbox and add the serial number. Then on execution of the function use document.querySelectorAll to get all the checked checkbox.
document.querySelectorAll will give a nodelist. To use the array method map it is first converted to array using spread operator .... Array method map is used here to return an array of the serial numbers which is retrieved from data attribute
function chkcontrol(j) {
var sum = 0;
const checkedBoxes = []
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("The total points used can't be more than 500")
//return false;
}
remaining = 500 - sum;
document.getElementById("msg").innerHTML = "<b>Points Used: </b>" + sum + "<br><b>Remaining Points: </b>" + remaining;
}
// added code here
const box = [...document.querySelector('form[name="form1"]')
.querySelectorAll('input[name="ckb"]:checked')]
.map(item => item.dataset.serial);
console.log(box)
}
<form name='form1'>
<table>
<tr>
<th>Select</th>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123001' value='120' onclick='chkcontrol(0)' ;> Serial# 123001 (value = 120) </td>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123002' value='200' onclick='chkcontrol(1)' ;> Serial# 123002 - (value = 200) </td>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123003' value='350' onclick='chkcontrol(2)' ;> Serial# 123003 - (value = 350) </td>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123004' value='100' onclick='chkcontrol(3)' ;> Serial# 123004 - (value = 100) </td>
</tr>
</table>
</form>
<div id='msg'></div>

will you try that... ?
const
myForm = document.forms['my-forn']
ckb_n = ['ckb1', 'ckb2', 'ckb3', 'ckb4' ]
, pSum = document.querySelector('#p-sum span')
;
myForm.onsubmit = e =>
{
e.preventDefault() // disable submit for test
}
myForm.oninput = e =>
{
let total = ckb_n.reduce((sum,nam)=>
{
sum += myForm[nam].checked ? Number(myForm[nam].value) : 0
return sum
}
, 0)
if (total > 500)
{
e.target.checked = false
let label = e.target.closest('label')
label.classList.add('errarum')
setTimeout(_=>{label.classList.remove('errarum')}, 2000)
alert("Sum of the selection can't be more than 500")
}
else
pSum.textContent = total
}
label {
display : block;
cursor : pointer;
}
.errarum {
color : red;
}
<form name="my-forn">
<label>
<input type="checkbox" name="ckb1" value="120" >
Serial# 123001 (value = 120)
</label>
<label>
<input type="checkbox" name="ckb2" value="200" >
Serial# 123002 (value = 200)
</label>
<label>
<input type="checkbox" name="ckb3" value="350" >
Serial# 123003 (value = 350)
</label>
<label>
<input type="checkbox" name="ckb4" value="100" >
Serial# 123004 (value = 100)
</label>
</form>
<p id="p-sum"> Sum : <span>0</span><p>

Related

How to insert price based on checkbox checked

I have a form where I calculate the price based on the checkboxes checked. But I am having trouble as its not updating the final price correctly. I did some jQuery coding but it's not functioning properly. How can I debug the code and fix it?
//Price Calculator
$(document).ready(function(){
function Calculator(){
let totalAmount = 0;
if($('input[datasource=service_0]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 395;
return totalAmount;
}else if($('input[datasource=service_1]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 392;
return totalAmount;
}else if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2) {
totalAmount = 397;
return totalAmount;
}
}
//Insert Updated Amount to Budget field
$("input[type=checkbox]").on("click", function(){
if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2){
$("input[name=wpcf-book-amount]").val(Calculator());
} else{
$("input[name=wpcf-book-amount]").val(Calculator());
}
})
})
<div class="extra-services">
<ul>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="5" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_0">
<label for="wpcf-additional-services">Cot (EUR 5)</label>
</li>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="2" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_1">
<label for="wpcf-additional-services">BABY CHAIR (EUR 2)</label>
</li>
</ul>
<input type="text" name="wpcf-booking-amount" id="booking_field" placeholder="Booking Amount (System Generated)" readonly>
</div>
Form containing the fields responsible to calculate the booking amount
<html>
<head></head>
<body>
<input type="checkbox" id="1st" onclick="ge()" value=500>
<label for="1st"> I have a bike</label><br>
<input type="checkbox" id="2nd" onclick ="ye()" value=200>
<label for="2nd"> I have a car</label>
<input type="number" id="here" value="0">
<script>
var amt = 0;
var st = document.getElementById("1st");
var nd = document.getElementById("2nd");
var num = document.getElementById("here");
function ge() {
if(st.checked == true ){
var g = parseInt(st.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(st.value);
num.value = amt;
}
}
function ye() {
if(nd.checked == true){
var g = parseInt(nd.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(nd.value);
num.value = amt;
}
}
</script>
</body>
</html>
Here you go if it's only for two checkbox this will work, for live demo click here

Get checkbox values with different class name in the same div id - jquery mvc

I am trying to get the values of checkboxes which are in the same divid but have different class name.
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="CurrentYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="PreviousYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="LastYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
With above code, I am able to populate data in a table with multiple checkboxes, but unable to get the value of the checkbox where the class name is something other than EntityCheck. Below is my jQuery function:
function GetSelectedEntities() {
var entities = "";
$("#divEntities").find('td').each(function (i, el) {
var checkbox = $(this).find('input.EntityCheck');
//var check1 = $(this).find('CurrentYear');
//var check2 = $(this).find('PreviousYear');
//var check3 = $(this).find('LastYear');
var check1 = $('.CurrentYear').val();
var check2 = $('.PreviousYear').val();
var check3 = $('.LastYear').val();
if (checkbox != undefined && $(checkbox).length > 0 && $(checkbox).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "|" + EntityData;
}
}
});
return entities;
}
jQuery function is invoked on a button click event:
<button style="font:normal 9pt Arial;height:30px;width:100px;border-radius:5px; border:none; background-color:royalblue; color:white" id="btnAdd" onclick="GetSelectedEntities(event);">
Add
</button>
I tried by giving the same class name to all the checkboxes but the problem was that I was able to get the values of the year checkbox, even if the CompanyName was not selected. I need the year values only if the CompanyName checkbox is checked and it's corresponding years. I also tried by giving the id='' to the year checkbox, but could not get the values.
I am unable to figure where I am going wrong. What is that I need to change in my jQuery to get the expected result?
Something like this would work:
$('#btnAdd').on('click', function(){
var checked = $('table').find('input:checked');
checked.each(function(){
alert($(this).closest('td').text());
//do your stuff here..
});
});
Se working fiddle: https://jsfiddle.net/c8n4rLjy/
I had to make changes to get the desired solution. Please find the solution below:
<tr>
<td colspan="4" align="center">
<div id="divEntities" style="width:100%;height:150px;overflow-y:scroll;align:center;">
<table cellspacing="2" cellpadding="2" width="95%" align="center" border="1">
#{
var i = 0;
while (i < Model.CompanyMaster.Count)
{
<tr>
<td style="width:50%" hidden="hidden"><input type="checkbox" class="EntityCheck" id="chkCompanyId" /> #Model.CompanyMaster[i].COMPANYID</td>
#if ((i + 1) < Model.CompanyMaster.Count)
{
<td><input type="checkbox" class="EntityCheck" /> #Model.CompanyMaster[i + 1].COMPANY_NAME</td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-1).Year </td>
<td><input type="checkbox" class="chkYear" /> #DateTime.Now.AddYears(-2).Year </td>
}
else
{
<td></td>
}
</tr>
i = i + 1;
}
}
</table>
</div>
</td>
</tr>
jQuery:
function GetSelectedEntities() {
var entities = "";
var CompanySelected = false;
var counter = 0;
$("#divEntities").find('td').each(function (i, el) {
counter = counter + 1
var checkbox = $(this).find('input.EntityCheck');
var checkboxyear = $(this).find('input.chkYear');
if (counter == 2) {
if (checkbox != undefined) {
if ($(checkbox).prop('checked') == true) {
CompanySelected = true;
var EntityData = jQuery.trim($(this).text());
if (entities == "") {
entities = EntityData;
}
else {
entities = entities + "-" + EntityData;
}
}
else {
CompanySelected = false;
}
}
}
if (counter > 2) {
if (CompanySelected == true) {
if (checkboxyear != undefined) {
if ($(checkboxyear).prop('checked') == true) {
var EntityData = jQuery.trim($(this).text());
entities = entities + "|" + EntityData;
}
}
}
}
if(counter == 5)
{
counter = 0;
}
});
return entities;
}

Exclude certain rows while calculating the minimum value

I have the following table and I need to find the minimum value in that column.
In this case the value is 20.
However, I need to exclude the last 2 part names and use the rest of the values in the cell to calculate the minimum. In that case the minimum value should be 100.
Here is the code i have for calculating the minimum:
function getMin() {
var maximum = 0;
jQuery(".used").each(function() {
$used= jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
maximum = (value > maximum) ? value : maximum;
});
var min = maximum;
jQuery(".used").each(function() {
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
min = (value < min) ? value : min;
});
jQuery(".minimum").val(min);
}
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="getMin();" readonly>cycles</div>
I couldn't find a way to exclude the last 2 values here. The number of rows can also differ and is not fixed so I need to exclude it based on those 2 string values. Any help is appreciated!! Thank you in advance!
Here is a quick and dirty solution. Loop through the parent object of each row, and ignore the value of used if the label (text) is one of those strings.
I also updated the minimum function to use the math.min on an array of values.
function getMin() {
let vals = [];
$(".row").each(function() {
if ($(this).find("label").html() != "Ignore") {
$used = $(this).find(".used").val();
var usedValue = $used.replace(/,/g, "");
vals.push(parseFloat(usedValue));
}
});
let min = Math.min(...vals);
$(".minimum").val(min);
}
getMin();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<label>Ignore</label>
<input type="text" class="used" value=41>
</div>
<div class="row">
<label>Keep</label>
<input type="text" class="used" value=222>
</div>
<div class="row">
<label>Keep</label>
<input type="text" class="used" value=200>
</div>
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="" readonly>cycles</div>
I would mark these different rows in HTML somehow, let's say with excluded class. Hardcoding the labels in JavaScript asks for trouble.
Here's an example, using excluded class for these two last <tr>:
const min = Math.min(...$(':not(.excluded) .used').map(function () {
return Number($(this).val());
}).get());
You could do it like this: Exclude in your each() function every <tr> that has a first column that contains any of the 2 strings you want to exclude:
function getMin() {
var maximum = 0;
jQuery(".used").each(function() {
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
maximum = (value > maximum) ? value : maximum;
});
var min = maximum;
jQuery("tr").each(function() {
var check = jQuery(this).find("td:nth-child(1)").text();
if (!check.includes("Fan Blade") && !check.includes("Annulus Filler"))
{
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
min = (value < min) ? value : min;
}
});
jQuery(".minimum").val(min);
}
getMin();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td></td>
<td></td>
<td><input class="used" value="100" /></td>
</tr>
<tr>
<td>Fan Blade (26 off)</td>
<td></td>
<td><input class="used" value="50" /></td>
</tr>
<tr>
<td>Annulus Filler (26 off)</td>
<td></td>
<td><input class="used" value="50" /></td>
</tr>
</table>
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="getMin();" readonly>cycles</div>

JavaScript array application

I'm trying to create a sample accounting system, the checkbox can be add to the total after it's checked and the input text is the amount of the money.
but my result keep getting zero, I can't figure it out.
Anyone can help me handle this problem?
I've test that the length of total_ary is 0, I think that is the mainly problem
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount").value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You do
document.getElementsByName("amount").value
but getElementsByName returns a collection, not an element.
You do
var total_ary = [];
// ... code that doesn't reference total_ary
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
But since the code in between doesn't reference total_ary, the total ends up being 0.
From a selected checkbox, you need to navigate to the associated input:
document.getElementsByName("amount")[i].value
since i is the cb index you're iterating over, the same i in the amount collection will refer to the input you need.
Or, more elegantly, just navigate to the next element in the DOM when a checkbox is checked, and take the number for each product's price from the DOM too. You can also select only the checked checkboxes immediately with a :checked selector, and attach the event listener using addEventListener (instead of an inline handler; inline handlers should be avoided)
document.querySelector('button').addEventListener('click', () => {
let total = 0;
for (const input of document.querySelectorAll('[name=cb]:checked')) {
const price = input.nextSibling.textContent.match(/\d+/)[0];
const amount = input.nextElementSibling.value;
total += price * amount;
}
document.getElementById("result").innerHTML = total + "元";
});
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input><br>
<input type="checkbox" name="cb" checked>$20:<input><br>
<input type="checkbox" name="cb" checked>$30:<input><br>
</fieldset>
<button>Count</button>
<p>Total = <span id="result">
document.getElementsByName() returns a collection of elements. so calling value property will not work there as it does not have such property.
You can hold input elements with amount_inputs variable and iterate over it (in the example below by using spread syntax and Array.reduce())
And with Array.reduce() you can calculate the sum of the prices. There is no need for var amount = [] and var total_ary = [] variables.
Hope this helps
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount_inputs = document.getElementsByName("amount")
var total = 0;
var price = [10, 20, 30];
total = [...input_cb].reduce((total, cb, i) => {
if(cb.checked){
total += (parseInt(amount_inputs[i].value) || 0) * price[i]
// ^^^^^^^^^ This is to avoid NaN multiplication
}
return total
},0);
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Use Index while retrieving the element from document.getElementsByName("amount");
Use for loop on amount array not on total_ary
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount")[i].value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += isNaN(parseInt(total_ary[i])) ? 0 : parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You have made a few mistakes:
(1) If you want to keep all the checkboxes checked at initial stage
use checked="true" in place of checked
(2) getElementsByName("amount") returns an array, so you should use the index as well
(3) total_ary length is 0 initially.. therefore, you should run the loop with input_cb. (Here, you can do both the task with a single loop: refer code below)
Refer the code with corrections:
<!DOCTYPE html>
<html>
<head>Order sys
<script>
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked){
amount.push(parseInt(document.getElementsByName("amount")[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
total += parseInt(amount[i] * price[i]) //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
</script>
</head>
<body>
<fieldset>
<input type = "checkbox" name="cb" checked="true">$10:<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked="true">$20:<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked="true">$30:<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
</body>
</html>
You can refactor your code:
Fist use inputs of type number <input type="number" name="amount"> to accept only numbers from your end users
Then, you can work with indexed arrays like [...document.querySelectorAll('input[name="cb"]')] and loop only one time with Array.prototype.reduce() to get the total
Code example:
function Totalamount() {
const inputNumberArr = [...document.querySelectorAll('input[name="cb"]')]
const inputAmountArr = [...document.querySelectorAll('input[name="amount"]')]
const priceArr = [10, 20, 30]
const total = inputNumberArr.reduce((a, c, i) => {
const num = c.checked ? +inputAmountArr[i].value : 0
return a + num * priceArr[i]
}, 0)
document.getElementById('result').innerHTML = '$' + 0
document.getElementById('result').innerHTML = '$' + total
}
<fieldset>
<input type="checkbox" name="cb" checked> $10:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $20:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $30:
<input type="number" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Is this what you are looking for?
Errors that I identified.
Making use of document.getElementsByName("amount").value instead of making the respective amount field you were making use of the global selector.
Trying to loop total_ary array instead of amount array.
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amountInput = document.getElementsByName('amount');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked && amountInput[i].value){
amount.push(parseInt(amountInput[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type = "checkbox" name="cb" checked>$10
<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked>$20
<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked>$30
<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">

get the sum of two checkbox on check

hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>
var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>
You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>

Categories

Resources