I am trying to make the total of the price of checkbox values given to the function. My value attribute stores the id of my database so I can not assign a price to the value tag.
function UpdateCost(elem) {
let total = Number(elem.value);
if (isNaN(total)) {
total = 0;
}
if (elem.checked === true) {
total = Number(elem.value);
} else {
total -= Number(elem.value);
}
alert(total);
document.getElementById('total').value = total.toFixed(0);
}
<form>
<input type="checkbox" value="1" onclick="UpdateCost(20);" /> Price = 20
<input type="checkbox" value="2" onclick="UpdateCost(25);" /> Price = 25
<input type="checkbox" value="3" onclick="UpdateCost(30);" /> Price = 30
<input type="checkbox" value="4" onclick="UpdateCost(20);" /> Price = 40
<input type=text id=total value=0>
</form>
CodePudding user response:
you can use the following function:
function UpdateCost() {
var checkboxes = document.getElementsByName('checkbox[]');
var len = checkboxes.length;
var result = 0;
for (var i = 0; i < len; i ) {
if (checkboxes[i].checked) {
result = result Number(checkboxes[i].value);
}
}
document.getElementById('total').innerHTML = result;
}
CodePudding user response:
You can use data-
attributes to achieve it.
let total = 0;
function UpdateCost(element) {
if (element.checked === true) {
total = Number(element.getAttribute('data-price'));
} else {
total -= Number(element.getAttribute('data-price'));
}
document.getElementById('total').innerHTML = total.toFixed(0);
}
<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" value="1" onclick="UpdateCost(this);" data-price="20" /> Price = 20
<input type="checkbox" value="2" onclick="UpdateCost(this);" data-price="25" /> Price = 25
<input type="checkbox" value="3" onclick="UpdateCost(this);" data-price="30" /> Price = 30
<input type="checkbox" value="4" onclick="UpdateCost(this);" data-price="40" /> Price = 40
<div id="total"> </div>
</form>
</body>
</html>
CodePudding user response:
You can try this
https://jsfiddle.net/3xq8zojg/
<form>
<input type="checkbox" value="1" onclick="UpdateCost(this);" />
<input type="checkbox" value="2" onclick="UpdateCost(this);" />
<input type="checkbox" value="3" onclick="UpdateCost(this);" />
<input type="checkbox" value="4" onclick="UpdateCost(this);" />
<div id="total"> </div>
</form>
var total = 0;
function UpdateCost(elem) {
alert(elem.value);
if (elem.checked === true) {
total = total Number(elem.value);
} else {
total = total -Number(elem.value);
}
console.log(total)
document.getElementById('total').value = total.toFixed(0);
}