Add Value To Javascript Variable When Checkbox Is Checked
This is the simple app for calculating the total price of selected elements of computer hardware. It should work with innerHTML and change it dinamically. The problem is that with
Solution 1:
There are a few problems
- You need to call
document.getElementById('total').innerHTML = price;
insidecheck
so that it updates when you click the checkbox; - You can't have multiple items with the same ID. I changed them to id_1, id_2, id_3
- You need to add to the existing value in the
add
variable - You have to hookup change for all the checkboxes, not just the first one.
Change your code to the following http://jsfiddle.net/mendesjuan/3ja4X/3/
function check() {
var basic = 300;
varadd = 0;
if(document.getElementById("id_1").checked) {
add += 120;
}
if(document.getElementById("id_2").checked) {
add += 40;
}
if(document.getElementById("id_3").checked) {
add += 90;
}
var p = basic + add;
var price = p + " €";
document.getElementById('total').innerHTML = price;
}
check();
For even cleaner code, you can use the following http://jsfiddle.net/mendesjuan/3ja4X/4/
functionupdateTotal(){
var basic = 300;
var add = 0;
var form = document.getElementById('form');
// Store the value for each item in the checkbox so// you don't need to have three separate `if`s and IDs for them.var checkboxes = form.getElementsByClassName('addon');
for (var i=0; i < checkboxes.length; i ++) {
if (checkboxes[i].checked) {
add += parseInt(checkboxes[i].value, 10);
}
}
var p = basic + add;
var price = p + " €";
document.getElementById('total').innerHTML = price;
}
// Hookup handlers from JS, not in the HTML from a single // place using event delegationdocument.getElementById('form').addEventListener('change', updateTotal);
Solution 2:
Add your calculations inside the check function, or make it calculate after the numbers are added:
function check(){
if(document.getElementById("id_1").checked) {
add = 120;
}
if(document.getElementById("id_1").checked) {
add = 40;
}
if(document.getElementById("id_1").checked) {
add = 90;
}
var p = basic + add;
var price = p + " €";
document.getElementById('total').innerHTML = price;
}
This the code does not only run once when the page is loaded.
Post a Comment for "Add Value To Javascript Variable When Checkbox Is Checked"