I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used name="items[]" to get the values i was wondering if there is a way to use ID or Class instead of the name.Any help would be appreciated in advance .
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate()
{
initVariable();
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.innerHTML +=count;
taxFeild.innerHTML+=(parseFloat(tax*count));
Total.innerHTML+= (tax*count) + count;
}
btn.addEventListener('click',Calculate);
function initVariable()
{
count =0;
ItemTotal.innerHTML="Item Total: ";
taxFeild.innerHTML =" Tax: ";
Total.innerHTML ="Total with Tax: ";
}
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>
<head>
<title>Test</title>
</head>
<body>
<div class = "container">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
</div>
<button id="btn">Calculate</button>
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</body>
</html>
If you have more than one its not correct to use same ID.
you can use de class and select it with document.querySelectorAll('.items')
The possible variants could be to use querySelectorAll or getElementsByClassName:
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)
<input type="checkbox" class="items" value='7.99' id="item1"> Hamburger ($7.99)
const checkboxes = document.getElementsByClassName('items');
// OR
const checkboxes = document.querySelectorAll('.items');
Or you still could use name attribute on input (instead of class):
const checkboxes = document.querySelectorAll('input[name="items[]"]');
You can select elements by their class. I would recommend using jQuery for this, but it can also be done in pure JavaScript. Let's assuming that we have three basic checkboxes (this is pseudo code):
<input type="checkbox" class="form-control" value="7.99">
<input type="checkbox" class="form-control" value="9.99">
<input type="checkbox" class="form-control" value="8.99">
<button class="btn btn-primary" type="button">
Calculate
</button>
We could use jQuery to iterate over each element with the class name ".form-control" in this scenario:
$(document).ready(function() {
const tax = 0.05;
$('.btn').on('click', function() {
let total = 0;
$('.form-control').each(function() {
if($(this).is(':checked')) {
let val = parseFloat($(this).val());
total += val;
}
});
if(total > 0) {
total += tax;
alert('Your total is $' + total);
}
});
});
Without jQuery you would do something such as:
const checks = document.getElementByClassName('form-control');
and then you could run an checks.each();
As a side not, do not give elements the same ID name or else JavaScript will not know which element you are trying to select. If you are going to select elements based on their id, make sure they have different ID's.
Related
How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total
What I want is for it to reset and calculate the new total with the new item added.
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate()
{
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.textContent += count;
taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
Total.textContent += ((tax*count) + count).toFixed(2);
}
btn.addEventListener('click',Calculate);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
<input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
<input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
<button id="btn">Calculate</button>
</div>
</div>
<div class="column" >
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</div>
<script src="java.js"></script>
</body>
</html>
You should:
Declare the count variable inside the Calculate function, so that it starts from 0 every time the button is clicked
Instead of +=ing to the ItemTotal, TotalWithTax, etc fields, create an inner element that you assign to the text to instead. So, for example, instead of
<p id="ItemTotal"> Item Total: </p>
use:
<p> Item Total: <span id="ItemTotal"></span></p>
This way, whenever the button is clicked, you can simply assign to the ItemTotal, overwriting whatever was there previously.
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks = document.querySelectorAll('.items');
var ItemTotal = document.getElementById('ItemTotal');
var Total = document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate() {
let count = 0;
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) {
count += parseFloat(checks[i].value);
}
}
ItemTotal.textContent = count;
taxFeild.textContent = (parseFloat(tax * count).toFixed(2));
Total.textContent = ((tax * count) + count).toFixed(2);
}
btn.addEventListener('click', Calculate);
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
<input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
<input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
<button id="btn">Calculate</button>
</div>
</div>
<div class="column">
<div id="Sums">
<p> Item Total: <span id="ItemTotal"></span></p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
</div>
</div>
</div>
You might also consider surrounding the inputs with <label>s, to make them more clickable:
var taxRate = 0.05;
var checks = document.querySelectorAll('.items');
var subtotalSpan = document.getElementById('ItemTotal');
var taxSpan = document.getElementById("Tax");
var totalSpan = document.getElementById('TotalWithTax');
function Calculate() {
let subtotal = 0;
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) {
subtotal += parseFloat(checks[i].value);
}
}
const tax = taxRate * subtotal;
const total = tax + subtotal;
subtotalSpan.textContent = subtotal;
taxSpan.textContent = tax.toFixed(2);
totalSpan.textContent = total.toFixed(2);
}
var btn = document.getElementById("btn");
btn.addEventListener('click', Calculate);
#checkBoxes > label {
cursor: pointer;
}
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<label><input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)</label><br>
<label><input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)</label><br>
<label><input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)</label><br>
<label><input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)</label><br>
<label><input type="checkbox" class="items" value='5.99'> Side salad ($5.99)</label><br>
<button id="btn">Calculate</button>
</div>
</div>
<div class="column">
<div id="Sums">
<p> Item Total: <span id="ItemTotal"></span></p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
</div>
</div>
</div>
You can use the onblur event on your calculator button. The onblur event occurs when you click off of an object. After a user clicks the "calculate" button, when they click anywhere else, the onblur function will call.
You can find out more about the onblur event at: https://www.w3schools.com/jsref/event_onblur.asp
W3Schools has a lot of easy to learn information. Here are other events which may prove to be useful in the future (or for expanding this project): https://www.w3schools.com/jsref/dom_obj_event.asp
A simple reset function can reset your counter and your paragraph tags.
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
// RESET YOUR CALCULATOR FIELDS & COUNT
function resetCalc(){
count = 0;
ItemTotal.textContent = "Item Total: ";
taxFeild.textContent = "Tax: ";
Total.textContent = "Total with Tax: ";
}
function Calculate()
{
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.textContent += count;
taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
Total.textContent += ((tax*count) + count).toFixed(2);
}
btn.addEventListener('click',Calculate);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
<input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
<input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
<!-- NOTICE THE ONBLUR -->
<button id="btn" onblur="resetCalc();">Calculate</button>
</div>
</div>
<div class="column" >
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</div>
<script src="java.js"></script>
</body>
</html>
Problem seems to be plus sign when asigning content. Just replace += with = and it should work
ItemTotal.textContent = count;
taxFeild.textContent = (parseFloat(tax*count).toFixed(2));
Total.textContent = ((tax*count) + count).toFixed(2);
And place captions in span like this:
<p> Item Total:<span id="ItemTotal"></span> </p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
You can add count = 0; on the first line of function Calculate() { .... } so it will gives you a new total every time your list changes.
To update the field and keep the content intact.
const taxValue = tax * count;
total = taxValue + count;
ItemTotal.innerText = "Item Total:" + count;
taxFeild.innerText = "Tax:" + (parseFloat(taxValue).toFixed(2));
Total.innerText = "Total with Tax:" + (parseFloat(total).toFixed(2));
I'm trying to display a total value of all the checkboxes that are checked
I've tried only this solution
my description is quite precise and self-explanatory
Javascript function
How to display the total of all checkboxes that are checked. Trying to display the total price by calculating all the checkboxes that are checked.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>On the go</title>
<link rel="stylesheet" type="text/css" href="menu.scss">
<script>
function calcAndShowTotal() { **
* // declaring the name and total***
var hotbeverage = document.querySelectorAll('input[name="hotbeverage"]');
var total = 0; **
* // checking if any checkboxes have been selected***
for (i = 0; i < hotbeverage.length; i++) { **
* // if the checkbox is selected add the value to total***
if (hotbeverage[i].checked) {
total = total + hotbeverage[i].value;
}
document.getElementById("amount").value = "You order total is R" + total;
}
</script>
***// adding checkboxes***
</head>
<body>
<h1>Hot Beverages</h1>
<div id="pricelist">
<input type="checkbox" name="hotbeverage" value="item1" price="25.00">Americano <b>R25.00</b><br>
<input type="checkbox" name="hotbeverage" value="item2" price="2">Caffe Latte <b>R30.00</b><br>
<input type="checkbox" name="hotbeverage" value="item3" price="3">Cappuccino <b>R15.00</b><br>
<input type="checkbox" name="hotbeverage" value="item4" price="4">Hot Chocolate<b>R20.00</b><br>
<input type="checkbox" name="hotbeverage" value="item5" price="5">Chai Latte <b>R20.00</b><br>
<input type="checkbox" name="hotbeverage" value="item6" price="6">ButterScotch latte<b>R28.00</b><br>
<input type="text" id="amount" value="0" />
</div>
</body>
</html>
I want the text field to populate with the value
The main problem comes when you're trying to calculate the value of the input when the real value is in the price attribute, so you can change .value by .getAttribute('price').
NOTE: It's always better to use data-* attribute when you need a custom attribute, so data-price will be more efficient, then you can get the value like :
parseFloat( hotbeverage[i].dataset.price );
document.querySelector('#calc').addEventListener('click', calcAndShowTotal);
function calcAndShowTotal() {
var hotbeverage = document.querySelectorAll('input[name="hotbeverage"]');
var total = 0;
for (i = 0; i < hotbeverage.length; i++) {
if (hotbeverage[i].checked) {
total += parseFloat( hotbeverage[i].getAttribute('price') );
}
}
document.getElementById("amount").value = "You order total is R " + total;
}
<h1>Hot Beverages</h1>
<div id="pricelist">
<input type="checkbox" name="hotbeverage" value="item1" price="25.00">Americano <b>R25.00</b><br>
<input type="checkbox" name="hotbeverage" value="item2" price="2">Caffe Latte <b>R30.00</b><br>
<input type="checkbox" name="hotbeverage" value="item3" price="3">Cappuccino <b>R15.00</b><br>
<input type="checkbox" name="hotbeverage" value="item4" price="4">Hot Chocolate<b>R20.00</b><br>
<input type="checkbox" name="hotbeverage" value="item5" price="5">Chai Latte <b>R20.00</b><br>
<input type="checkbox" name="hotbeverage" value="item6" price="6">ButterScotch latte<b>R28.00</b><br>
<input type="text" id="amount" value="0" />
</div>
<button id="calc">Calculate</button>
To display the total of all checkboxes that are checked and display the total price by calculating all the checkboxes that are checked you can use following code:
html tag:
test 1
test 2
test 3
test 4
javaScript code:
jQuery(document).ready(function($) {
var sum = 0;
$('#pakker :checkbox').click(function() {
sum = 0;
$('#pakker :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#sum').html(sum);
});
});
Please also refer following link for more details.
http://jsfiddle.net/vaKWs/6/
Following are mistakes in the code:
You are not calling the function calcAndShowTotal. You should attach event to all the checkboxes to see change.
You are adding value but you should add its price. Use getAttribute to checkbox's price.
In your loop you are declaring global variable i. Use let before it.
let hotbeverage = document.querySelectorAll('input[name="hotbeverage"]');
hotbeverage.forEach(x => {
x.addEventListener('change',calcAndShowTotal)
})
function calcAndShowTotal() {
// declaring the name and total***
var total = 0;
// checking if any checkboxes have been selected***
for (let i = 0; i < hotbeverage.length; i++) {
// if the checkbox is selected add the value to total***
if (hotbeverage[i].checked) {
total = total + (+hotbeverage[i].getAttribute('price'))
}
document.getElementById("amount").value = "You order total is R" + total;
}
}
<h1>Hot Beverages</h1>
<div id="pricelist">
<input type="checkbox" name="hotbeverage" value="item1" price="25.00">Americano <b>R25.00</b><br>
<input type="checkbox" name="hotbeverage" value="item2" price="2">Caffe Latte <b>R30.00</b><br>
<input type="checkbox" name="hotbeverage" value="item3" price="3">Cappuccino <b>R15.00</b><br>
<input type="checkbox" name="hotbeverage" value="item4" price="4">Hot Chocolate<b>R20.00</b><br>
<input type="checkbox" name="hotbeverage" value="item5" price="5">Chai Latte <b>R20.00</b><br>
<input type="checkbox" name="hotbeverage" value="item6" price="6">ButterScotch latte<b>R28.00</b><br>
<input type="text" id="amount" value="0" />
</div>
I'm trying to create a function that will disable all remaining unchecked checkboxes in my form after 5 boxes are checked.
I am able to pull the values(using .length) to verify that 5 checkboxes have in fact been checked, I cannot get the disable() function wired to the remaining checkboxes properly. Any suggestions would be greatly appreciated.
JS logic is below:
document.addEventListener('DOMContentLoaded', () => {
let Checkboxes =
document.querySelectorAll('input[type="checkbox"]').length <-verifies checkbox total;
Checkboxes.addEventListener('click', (event)=>{
event.preventDefault();
checkboxLimiter();
});
});
function checkboxLimiter() {
let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length; <-verifies "checked" checkbox total;
if (markedBoxCount == 5){
disable();
}
}
function disable() {
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)') <-selector for remaining "unchecked" checkboxes;
;
unmarkedBoxCount.disabled = true;
And here is the HTML for reference:
<div id="strengthsJar">
<div id="stJar">
<p>Strategic Thinking</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="st-attribute" value="(1,1)"></label>
</div>
<div id="eJar">
<p>Executing</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="e-attribute" value="(1,-1)">
Achiever
</label>
</div>
<div id="rbJar">
<p>Relationship Building</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="rb-attribute" value="(-1,1)">
Adaptability
</label>
</div>
<div id="iJar">
<p>Influencing</p>
<label class="checkbox-inline" for="usertype"> <input
type="checkbox" name="attribute" id="i-attribute" value="(-1,-1)">
Activator
</label>
</div>
</div>
Okay a couple of things first:
1.)
let Checkboxes = document.querySelectorAll('input[type="checkbox"]').length
doing this you will set the Checkboxes variable to the number equal to the length of the array of all the checkboxes in the document not to the array itself so you cannot add an eventlistener on a number.
2.)
Checkboxes.addEventListener('click', (event)=>{
event.preventDefault();
checkboxLimiter();
});
and
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)') ;
unmarkedBoxCount.disabled = true;
you cannot perform an operation on the whole array of DOM nodes all at once, you have to iterate over them and addlisteners or disable them one by one.
3.)
Checkboxes.addEventListener('click', (event)=>{
event.preventDefault();
checkboxLimiter();
});
you cannot check the checkbox if you prevent the default actions here.
Here is the working code, one difference is that I'm disabling the rest of the checkboxes after you check two of them as I didn't want to add more checkboxes to keep the example simple.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="strengthsJar">
<div id="stJar">
<p>Strategic Thinking</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="st-attribute" value="(1,1)">
</label>
</div>
<div id="eJar">
<p>Executing</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="e-attribute" value="(1,-1)"> Achiever
</label>
</div>
<div id="rbJar">
<p>Relationship Building</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="rb-attribute" value="(-1,1)"> Adaptability
</label>
</div>
<div id="iJar">
<p>Influencing</p>
<label class="checkbox-inline" for="usertype">
<input type="checkbox" name="attribute" id="i-attribute" value="(-1,-1)"> Activator
</label>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
let Checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < Checkboxes.length; i++)
Checkboxes[i].addEventListener('click', (event) => {
checkboxLimiter();
});
});
function checkboxLimiter() {
let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
if (markedBoxCount == 2) {
disable();
}
}
function disable() {
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
for (let i = 0; i < unmarkedBoxCount.length; i++)
unmarkedBoxCount[i].disabled = true;
}
</script>
</body>
</html>
There are couple of mistakes, so this will work for example
document.addEventListener('DOMContentLoaded', () => {
// we need to get all checkbox elements, not its length
let Checkboxes = document.querySelectorAll('input[type="checkbox"]')
// Checkboxes is nodelist, so we need to add event listener
// on every element in it, like this for example
Checkboxes.forEach( checkbox => {
checkbox.addEventListener('click', (event)=>{
checkboxLimiter();
});
});
});
function checkboxLimiter() {
let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
if (markedBoxCount == 3){
disable();
}
}
function disable() {
let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
// same thing as Checkboxes
unmarkedBoxCount.forEach(checkbox => {
checkbox.disabled = true
})
}
Your logic has some errors
Try this:
let Checkboxes = document.querySelectorAll('input[type="checkbox"]');
for(var i = 0; i < Checkboxes.length; i++) {
Checkboxes[i].addEventListener('change', function() {
checkboxLimiter(this);
});
}
function checkboxLimiter(checkbox) {
let markedBoxCount =
document.querySelectorAll('input[type="checkbox"]:checked').length
if (markedBoxCount > 2){
checkbox.checked = false;
};
};
In this example, I disable checkbox with 2 checkeds
I was trying to make a content score as a class assignment.
Assume : (The user sees a URL and then select the checkboxes that are assigned to issues . Each issue is assigned a score in a array.)
Whats working :
Individual checks are registered with their respective scores being displayed
Whats not working :
Can someone help me to update the score ( as the user checks the checkbox or unchecks).
I am assuming in future if i want to increase the issues I will be able to do that since it is in an array. (am i right)
(my week 4 in JS)
//Set up an array with the respective score
var code = new Array();
code["v1"] = 1;
code["v2"] = 2;
code["v3"] = 3;
code["v4"] = 5;
// As the user selects the checkbox I want to keep on adding the score and as the user unchecks I want to recalculate and display.
function getvalueScore() {
var score = 0;
//Get a reference to the form
var theForm = document.forms["contentForm"];
//Get a reference to the score from the "ContentForm"
var contentScore = theForm.elements["contentScore"];
// loop through each check box
for (var i = 0; i < contentScore.length; i++) {
//if the radio button is checked
if (contentScore[i].checked) {
// I want to calculate and keep updating the score
score = code[contentScore[i].value];
}
}
//return score
return score;
}
function calculateTotal() {
//calculation for final score
var scoreCard = getvalueScore();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Content Score is " + scoreCard;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
<!DOCTYPE html>
<html>
<head>
<title>Content Score</title>
<meta charset="utf-8">
<script src="formcalculations.js"></script>
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="contentForm" onsubmit="return false;">
<div>
<div class="cont_order">
Content Score</br>
<label>Please select the issues you see on the page to calculate the content score</label>
</br>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v1" onclick="calculateTotal()" />No content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v2" onclick="calculateTotal()" />Mediocre content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v3" onclick="calculateTotal()" />Obsolete content</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v4" onclick="calculateTotal()" />Irrelevant content</label>
<br/>
<br/>
<br/>
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>
In your code you assign last selected checkbox to score variable, so the only thing you need to do is to sum the scores with:
score += code[contentScore[i].value];
I am trying to create a javascript code for my website to do the calculations once a checkbox is checked. Each time i select a checkbox it should calculate the total price of the items.
This is my html code:
<form id="orderForm" action="#" method="get">
<section id="selectBook">
<h2>Select books</h2>
<?php
include_once('database_conn.php');
$sqlBooks = 'SELECT bookISBN, bookTitle, bookYear, catDesc, bookPrice FROM nbc_book b inner join nbc_category c on b.catID = c.catID WHERE 1 order by bookTitle';
$rsBooks = mysqli_query($conn, $sqlBooks);
while ($book = mysqli_fetch_assoc($rsBooks)) {
echo "\t<div class='item'>
<span class='bookTitle'>{$book['bookTitle']}</span>
<span class='bookYear'>{$book['bookYear']}</span>
<span class='catDesc'>{$book['catDesc']}</span>
<span class='bookPrice'>{$book['bookPrice']}</span>
<span class='chosen'><input type='checkbox' name='book[]' value='{$book['bookISBN']}' title='{$book['bookPrice']}' /></span>
</div>\n";
}
?>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen book(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £3.99 <input type="radio" name="deliveryType" value="home" title="3.99" checked = "checked" /> |
Collect from warehouse - no charge <input type="radio" name="deliveryType" value="trade" title="0" />
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
The code has been separated into tag.
This is my current javascript code which i have written:
var item = document.getElementsByClassName("item");
var chkbox = document.getElementsByTagName("input");
for(var i = 0; i < chkbox.length; i++){
chkbox[i].onchange = function(){
//Recalculate total
getTotal();
}
}
function getTotal(){
var total = 0.0;
for(var i = 1; i <= chkbox.length; i++){
//If the checkbox is checked, add it to the total
if(chkbox[i-1].checked){
total = total + parseFloat(chkbox[i].value);
}
}
return total;
document.getElementById("total").innerHTML = total;
}
I really need some experts to help me on this. Thank you.
In getTotal() you are returning before setting the value here:
return total;
document.getElementById("total").innerHTML = total;
Set the input with the value rather than innerHTHML.
document.getElementById("total").setAttribute("value", total);
I had to change the checked to be parseFloat(chkbox[i-1].title) to match the if statement
jsFiddle
The above example uses to products, the first priced at 1 and the second at 2.