How to reuse code block in javascript - javascript

I am new to learning javascript and apologize if this question is too basic. I have tried to search for a solution but nothing has been clear to me. I have created this code in this link.
https://jsfiddle.net/5p7wzy9x/3/
var btn = document.getElementById("calc");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
var totalTb = document.getElementById("total");
totalTb.value = count ? output : "NaN";
});
var btn = document.getElementById("calcTwo");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = (total / count);
var totalTb = document.getElementById("total");
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
My question is, how would I go about being able to use the same code for the second "grade" button without having to copy and pasting the same code?
I saw that you can use functions to invoke the same code block but am confused how I would go about it. I apologize if this question has already been answered, but I have diligently searched and tried to figure this out on my own. Thank you in advanced.

Instead of passing anonymous functions (functions with no names) to your event handlers as data:
btn.addEventListener("click", function() { ...
set up those functions as "function declarations" so that you can call them by name. Then, instead of passing them into the .addEventListner() method call, you reference them by name (without parenthesis next to the name).
Here's an example:
// Both buttons are configured to call the same event handling function:
document.getElementById("btn1").addEventListener("click", doSomething);
document.getElementById("btn2").addEventListener("click", doSomething);
function doSomething(){
console.log("Hello!");
}
<input type=button id="btn1" value="Click Me">
<input type=button id="btn2" value="Click Me">

Here is how you can combine common code in one function:
var btn = document.getElementById("calc");
var btn2 = document.getElementById("calcTwo");
var totalTb = document.getElementById("total");
btn.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output < Infinity ? output : "NaN";
});
btn2.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
function getTotal() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
return output;
}
<form id="form1">
<input class="value" type="text" value="80" /><br />
<input class="value" type="text" value="50" /><br />
<input class="value" type="text" value="15" /><br />
<input class="value" type="text" value="30" /><br />
<input class="value" type="text" value="90" /><br />
<br />
<input type="text" id="total" />
<button type="button" id="calc">Calculate</button>
<button type="button" id="calcTwo">Grade</button>
</form>

Related

Javascript form clears instantly and flashes one answer

I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.

What is the best way to combine and evaluate user input through javascript?

(I'm very new to this, please bear with me)
I'm making several modules that require user input and I want to somehow combine the input to produce an output. I was thinking of assigning each option a value and adding them together and creating an if/else statement to determine the output...
For example, if the user selects three options with values 1, 2, 3 and the statement says that any combined value greater than 5 will get a result of "Good", then the selected options will get a response of "Good" because when combined, they equal 6 (which is >5).
Does anyone know a better way, and/or can you direct me to some reference sites that might have what I'm looking for?
Thank you so much!! Any help is appreciated!!
Are you looking for something like this?
<form id="module1">
<input name="option1" type="checkbox" value="Orange"> Orange
<input name="option2" type="checkbox" value="Banana"> Banana
<input name="option3" type="checkbox" value="Apple"> Apple
<input name="option4" type="checkbox" value="Mango"> Mango
<input name="option5" type="checkbox" value="Pineapple"> Pineapple
</form>
<button id="evaluate" type="button">Evaluate</button>
<h4 id="result"></h4>
<h5 id="values"></h5>
<script type="text/javascript">
$(document).ready(function () {
var scoreConstants = {
'Mango': 100,
'Banana': 100,
'Pineapple': 200,
'Orange': 50,
'Apple': 250
};
var evalScore = function (selectedValues) {
var totalScore = 0;
$.each(selectedValues, function (k, v) {
totalScore += scoreConstants[v];
});
return totalScore;
}
var getScoreLabel = function (score) {
var scoreValue = 'Score: ';
if (score < 200) {
scoreValue += 'Average';
} else if (score >= 200 && score < 500) {
scoreValue += 'Good';
} else if (score >= 500) {
scoreValue += 'Excellent!';
}
return scoreValue;
}
$('body').on('click', '#evaluate', function (e) {
var $selectedValues = $('#module1').find('input:checked');
var selectedValues = [];
$selectedValues.each(function (k, v) {
var $selected = $(v);
selectedValues.push($selected.val());
});
var score = evalScore(selectedValues);
var scoreLabel = getScoreLabel(score);
var valueString = 'Selected: ';
if (selectedValues.length > 0) {
$.each(selectedValues, function (k, v) {
if (k === (selectedValues.length - 1)) {
valueString += v;
} else {
valueString += v + ', '
}
});
} else {
valueString += 'None';
}
var $result = $('#result');
$result.html(scoreLabel);
var $displayValues = $('#values');
$displayValues.html(valueString);
});
});
</script>
See the code working here:
https://jsfiddle.net/0x2L0dek/1
I think you are looking for this.
To see the result, check your console.
<input type="checkbox" class="chk" value=1>1</input><br>
<input type="checkbox" value=2 class="chk">2</input><br>
<input type="checkbox" value=3 class="chk">3</input><br>
<input type="checkbox" value=4 class="chk">4</input><br>
<button id="button1" onclick="checkSum()">Submit</button>
<script>
function checkSum(){
var chk = document.getElementsByClassName('chk');
sum = 0;
for(var i=0; chk[i]; ++i){
if(chk[i].checked){
sum = sum + parseInt(chk[i].value);
}
}
console.log(sum);
if(sum > 5){
console.log("Good");
}
}
</script>

jquery bunch of input values multiply by dynamic (another input)

I have a grouped product and that all group can buy within a page. Page has multiple quantity inputs (like 6). And another bulk quantity input.
What it must do is,
After setting the normal product quantities, those values must multiply by the bulk input value.
my code does the multiplication, but not as i expect. It just multiply by the current input value. I want to do as follows.
(1st attempt)
Eg : Input 1 Value = 5, Input 2 value = 2, Input 3 Value = 8. Bulk Value = 10
Results should be : Input 1 = 50, Input 2 = 20, Input 3 = 80
If we gain the bulk value by 1 (2nd attempt)
current Input 1 Value = 50, current Input 2 value = 20, current Input 3 Value = 80. new gained Bulk Value = 11
Results should be : Input 1 = 55, Input 2 = 22, Input 3 = 88
$('#multiply-value').change(function() {
var multiplied = $('#multiply-value').val();
var milti = 0;
var value_of = 0;
var test = 0;
if (this.getAttribute('value') === this.value) {
$(this).data('lastvalue', this.value);
} else {
if(this.value < $(this).data('lastvalue')){
var old = $(this).data('lastvalue');
console.log('decrement');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = $(this);
var old_v = $(this).data('lastvalue');
old_test = old_v.val();
test = qty_vals.val();
var cals = 0;
while(i < multiplied ){
cals = +old_test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
else{
console.log('increment');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = $(this);
test = qty_vals.val();
var cals = 0;
while(i <= multiplied ){
cals = +test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
// console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
$(this).data('lastvalue', this.value);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class=""bunch-of-inputs">
<input type="text" name="super_group[50]" maxlength="12" value="0" title="Qty" class="input-text qty">
<input type="text" name="super_group[50]" maxlength="12" value="0" title="Qty" class="input-text qty">
<input type="text" name="super_group[50]" maxlength="12" value="0" title="Qty" class="input-text qty">
</div>
<input id="multiply-value" type="number" value="1">
</div>
why not to store the original value of each field at another field rather than the value field ?
so the html will be :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class=""bunch-of-inputs">
<input type="text" name="super_group[50]" maxlength="12" value="5" title="Qty" class="input-text qty" data-default="5">
<input type="text" name="super_group[50]" maxlength="12" value="2" title="Qty" class="input-text qty" data-default="2">
<input type="text" name="super_group[50]" maxlength="12" value="8" title="Qty" class="input-text qty" data-default="8">
</div>
<input id="multiply-value" type="number" value="1" >
</div>
And the js will be:
$('#multiply-value').on('input',function() {
var multiplied = $('#multiply-value').val();
$('.input-text.qty').each(function() {
$(this).val($(this).data('default') * multiplied);
});
})
this way we don't need to store the previous value, we have the default value any time
/* modification start */
firsttime = true;
zero = true;
$('#multiply-value').change(function() {
if (firsttime && zero) {
$('.input-text.qty').each(function() {
this.setAttribute('value', $(this).val());
firsttime = false;
if($(this).val() != 0) {
zero = false;
}
});
}
/* modification end */
var multiplied = $('#multiply-value').val();
var milti = 0;
var value_of = 0;
var test = 0;
if (this.getAttribute('value') === this.value) {
$(this).data('lastvalue', this.value);
} else {
if (this.value < $(this).data('lastvalue')) {
var old = $(this).data('lastvalue');
console.log('decrement');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = $(this);
var old_v = $(this).data('lastvalue');
old_test = old_v.val();
test = qty_vals.val();
var cals = 0;
while (i < multiplied) {
cals = +old_test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
else {
console.log('increment');
$('.input-text.qty').each(function() {
var i = 1;
var qty_vals = this; // modified, write this instead of $(this)
test = qty_vals.getAttribute('value'); // modification here
var cals = 0;
while (i <= multiplied) {
cals = +test + +cals;
console.log(cals);
i++
}
$(this).val(cals);
test = 0;
});
}
// console.log(this.value < $(this).data('lastvalue') ? 'decrement' : 'increment');
$(this).data('lastvalue', this.value);
}
})
The first inputs are set to respective value attributes. If all of the inputs are zero, then the second inputs will act as first inputs and so on. Instead of test = qty_vals.value; write, test = qty_vals.getAttribute('value'); to get original non-zero values.

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

Unchecking a checkbox and modifying value of sum

I am trying to design a menu. If you check a box, then sum get added up and if you uncheck it, the sum is reduced. I face trouble in reducing the sum while unchecking the box and also the value of sum is not globally changed. Please help me out.
<head>
<script>
var sum=0;
function a(sum,num) {
sum=sum+num;
document.getElementById("demo").innerHTML=sum;
}
</script>
</head>
<body>
<input type="checkbox" name="Dal" id="dal" onclick=a(sum,10)>Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick=a(sum,20)>Rice<br>
<h1> Total Price is : </h1>
<p id="demo"> 0 </p>
</body>
Change the markup, add a value and a class, and remove the inline JS
<input type="checkbox" name="Dal" id="dal" value="10" class="myClass">Dal
<input type="checkbox" name="Rice" id="rice" value="20" class="myClass">Rice
<h1> Total Price is : </h1><p id="demo">0</p>
Then do
<script type="text/javascript">
var inputs = document.getElementsByClassName('myClass'),
total = document.getElementById('demo');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
}
}
</script>
FIDDLE
You can do something like this:
function a (elem, num) {
var k = (elem.checked) ? 1 : -1;
sum = sum + k * num;
document.getElementById("demo").innerHTML = sum;
}
And in the HTML:
<input type="checkbox" name="Dal" id="dal" onclick="a(this, 10);">Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick="a(this, 20);">Rice<br>
Try something like this:
var sum = 0;
function a(id, num) {
if(id.checked == true){
sum += num;
id.onclick = function() { a(id, num)};
}
else {
sum -= num;
id.onclick = function() { a(id, num)};
}
document.getElementById("demo").innerHTML=sum;
}
Fiddle: http://jsfiddle.net/95pvc/2/
My own take would involve removing the event-handling from the HTML (unobtrusive JavaScript) for easier maintenance in future, using data-* attributes to contain the price and using a class-name to identify the relevant ingredients, to give the following HTML:
<input class="ingredients" type="checkbox" name="Dal" data-price="10" id="dal" />Dal
<input class="ingredients" type="checkbox" name="Rice" data-price="20" id="rice" />Rice
<h1> Total Price is : </h1>
<p id="demo">0</p>
Which leads to the following JavaScript:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
for (var i = 0, len = ingredients.length; i < len; i++) {
ingredients[i].addEventListener('change', price);
}
JS Fiddle demo.
To avoid having to iterate through the relevant checkboxes, it might be better to wrap those input elements in a form, and then bind the event-handling to that form:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
document.getElementById('formID').addEventListener('change', price);
JS Fiddle demo.
References:
addEventListener().
element.getAttribute().
getElementsByClassName().
parseFloat().

Categories

Resources