Unchecking a checkbox and modifying value of sum - javascript

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().

Related

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>

Storing multiple values with different id in array - php,javascript

Multiple values are inputted using below code:
$c_num is the count of inputs. There are n number of inputs
$stud['stud_c'] is student codes, S01,S02,S05,S08,S19 .........
On a javascript function calculate(), a portion of id is passed.
code:
<input type="number" required id="c_m_<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>" name="c_m_<?php echo $c_num; ?>[<?php echo $stud['stud_c'];?>]" onkeypress="calculate('<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>','<?php echo $stud['stud_c'];?>')" class="num<?php echo $c_num; ?> " >
When I alert class1, i am getting corresponding output. But how to store multiple values with different id in array? How to store those inputted values in array num[] ? I also want to alert the total of these inputs.
Corresponding script for finding sum of n number of inputs:
function calculate(class1,class2){
var n = parseFloat(document.getElementById('count').value);
var num[] = parseFloat(document.getElementById('c_m_'+class1).value);
var total=0;
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
if (!isNaN(total)) {
document.getElementById('total_mark_'+class2).value = Math.round(total);
}
}
Try like this..
<script>
arr =[];
function calculate(class1)
{
//var n = parseFloat(document.getElementById('count').value);
var num = parseFloat(document.getElementById('c_m_'+class1).value);
arr.push(num);
var total=0;
var n =arr.length;
for (var i = 0; i <n; i++) {
total = total +arr[i];
}
alert(total);
}
</script>
Try this . array.push().And array declaration was wrong.use num=[] instead of num[] .
I don't know why use n on forloop length. if you originaly need the array length use with n=num.length
var num=[];
function calculate(class1)
{
var n = parseFloat(document.getElementById('count').value);
num.push(parseFloat(document.getElementById('c_m_'+class1).value));
var total=0;
//n=num.length if you need num array length use this
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
alert(total);
}
Assign a common attribute for the inputs and fetch them by this attribute. There are many ways to fetch nodes by attribute. To name a few:
parentNode.getElementsByClassName('className') fetches all the child nodes having specific class attribute;
parentNode.querySelectorAll('input[attribute="value"]') fetches a node list of all input tags having specific attribute value
using jQuery selector like 'input[attribute="value"]'
Example
(function() {
var inputs, i, total = 0;
inputs = document.forms.c.querySelectorAll("input[name='c_m[]']");
for (i = 0; i < inputs.length; i++) {
total += Number(inputs[i].value);
}
console.log(total);
})();
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>XXX</title>
</head>
<body>
<form name="c">
<input type="text" name="c_m[]" value="1" size="3" />
<input type="text" name="c_m[]" value="2" size="3" />
<input type="text" name="c_m[]" value="3" size="3" />
</form>
</body>
</html>
Note, you don't need to collect the input values into num array, if you only want to compute the sum of the values. Simply literate the nodes and collect their values. If for some reason you still want to collect the values into an array, use Array.prototype.push method:
var num = [];
for (i = 0; i < inputs.length; i++) {
num.push(inputs[i].value);
}
<script type="text/javascript">
var RECALCULATE = function(a,b) {
var rowtotal = 0;
n = new Array();
var count = document.getElementById('criteria_count').value;
for (i = 1; i <=count; i++) {
if (parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value) > 0) {
n[i] = parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value);
rowtotal += n[i];
}
}
document.getElementById('total_mark_'+b).value = rowtotal;
};
</script>

Trouble setting and adding array values javascript

I want to give each check box an integer value and then if the box is checked add the values and display the total in a text box with the ID="options". So far the code is not sending a value to the desired location. Any instruction on how to improve the code would be helpful. Thank you.
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ($5)
<input name="opt2" value="10" type="checkbox"> Lunch ($10)
<input name="opt3" checked="checked" value="0" type="checkbox"> Happy Hour (free!)
<input id="options" name="options" type="text">
</form>
</body>
</html>
<script>
function getOptions() {
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input"),
result = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += inputs[i].value;
document.getElementById("options").value = result;
}
}
}
getOptions();
</script>
You may need to attach onchange event handlers to the checkboxes as shown below. And you should parse inputs[i].value to a number using parseFloat() before adding it to result.
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input");
function getOptions() {
var result = 0;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += parseFloat(inputs[i].value);
}
}
document.getElementById("options").value = result;
}
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox") {
inputs[i].onchange = function () {
getOptions();
}
}
}
getOptions();
JSFiddle

Buttons with values, How to calculate a total price

First I'd like to say that i'm a very new beginner when it comes to java script with no other skills involved. I seem to be a little lost in my coding. I have two sets of options with three choices within each. Each choice has its own price. How do I calculate a total price?
JavaScript (included in HEAD)
var theForm = document.forms["pizzaOrder"];
var pizza_price = new Array();
pizza_price["meatLover"] = 15.50;
pizza_price["veggieLover"] = 12.50;
pizza_price["supreme"] = 20.00;
function getPizzaPrice() {
var pizzaPrice = 0;
var theForm = document.forms["pizzaOrder"]; //You already declared "theForm" at global scope - no need to redeclare it here to hold the same reference -crush
var pizzaType = theForms.elements["pizzaType"]; //Mispelled "theForm" here -crush
for(var i = 0; i < pizzaType.length; i++) {
if(pizzaType[i].checked) {
pizzaPrice = pizza_price[pizzaPrice[i].value];
break;
}
}
return pizzaPrice;
}
var extra_top = new Array()
extraTop["extraChees"] = 1.00;
extraTop["mushrooms"] = 1.10;
extraTop["anchovies"]-1.25; //Obvious syntax error here -crush
function getToppingPrice() {
var toppingPrice=0;
var theForm = document.forms["pizzaOrder"];
var extraTop = theForm.elements["extraTop"] //You forgot the semi-colon here -crush
for(var i = 0; i < extraTop.length; i++) {
if(extraTop[i].checked) {
toppingPrice = extra_top[extraTop.value];
break;
}
}
return toppingPrice;
}
function getTotal() //You're missing an opening bracket here -crush
var pizzaPrice = getPizzaPrice() + getToppingPrice();
document.getElementbyId('totalPrice').innerHTML = "Total Price for Pizza is $" + pizzaPrice;
//You're missing a closing bracket here -crush
HTML
<body onload="hideTotal">
<h1>Pizza To Go</h1>
<h2>Order Online</h2>
<form action="" id="PizzaOrder" onsubmit="return false;">
<p>Select Your Pizza!<br />
<input type="radio" name="pizzaType" value="meatLover" onclick="calculateTotal()"/> Meat Lover $12.50<br />
<input type="radio" name="pizzaType" value="veggieLover" onclick="calculateTotal()"/> Veggie Lover $12.50<br />
<input type="radio" name="pizzaType" value="supreme" onclick="calculateTotal()"/> Supreme $12.50<br />
<p>Add Extra Toppings!<br />
<input type="checkbox" name="extraTop" value="extraCheese" onclick="calculateTotal()"/> Extra Cheese $1<br />
<input type="checkbox" name="extraTop" value="mushrooms" onclick="calculateTotal()"/> Mushrooms $1.10<br />
<input type="checkbox" name="extraTop" value="anchovies" onclick="calculateTotal()"/> Anchovies $1.25<br />
</form>
</body>
I'm currently lost as it just doesnt seem to work. Any help is much appreciated.
Your code could stand to be cleaned up quite a bit in general, but your functional issue is that you should be using an object instead of arrays to hold your item prices. Cleanup notwithstanding, try something like this:
var pizza_price = {
"meatLover": 15.50,
"veggieLover": 12.50,
"supreme": 20.00
};
var extra_top = {
"extraChees": 1.00,
"mushrooms": 1.10,
"anchovies": -1.25
};
function getPizzaPrice() {
var pizzaPrice=0;
var theForm = document.forms["pizzaOrder"];
var pizzaType = theForms.elements["pizzaType"];
for(var i = 0; i < pizzaType.length; i++) {
if(pizzaType[i].checked) {
pizzaPrice += pizza_price[pizzaPrice[i].value];
}
}
return pizzaPrice;
}
function getToppingPrice() {
var toppingPrice=0;
var theForm = document.forms["pizzaOrder"];
var extraTop = theForm.elements["extraTop"];
for(var i = 0; i < extraTop.length; i++) {
if(extraTop[i].checked) {
toppingPrice += extra_top[extraTop[i].value];
}
}
return toppingPrice;
}
function getTotal() { return getPizzaPrice() + getToppingPrice(); }
If you want to create a jsfiddle I'll take a closer look.

Shortening JavaScript Function

I must admit, I don't know much about JavaScript that is why my question might sound little bit silly.
But what I'm trying to do is grab values from selected by name radio groups.
It looks like this
function calc() {
var op1 = document.getElementsByName('form[radio1]');
var op2 = document.getElementsByName('form[radio2]');
var op3 = document.getElementsByName('form[radio3]');
var result = document.getElementById('result');
result.value = 0;
result.value = parseInt(result.value);
for (i = 0; i < op1.length; i++) {
if (op1[i].checked) result.value = parseInt(result.value) + parseInt(op1[i].value);
}
for (i = 0; i < op2.length; i++) {
if (op2.options[i].selected) result.value = parseInt(result.value) + parseInt(op2[i].value);
}
for (i = 0; i < op3.length; i++) {
if (op3.options[i].selected) result.value = parseInt(result.value) + parseInt(op3[i].value);
}
return false;
}
And this is my form. Im using rs form for joomla.
<form action="index.php" enctype="multipart/form-data" id="userForm" method="post">
<input name="form[radio1]" value="25" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio1]" value="35" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input name="form[radio2]" value="20" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio2]" value="30" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input type="hidden" value="0" id="result" name="form[result]">
<input type="submit" class="rsform-submit-button" onclick="calc()" id="submit" name="form[submit]" value="submit">
And everything would be OK, as the function is working. the only trouble is that I have about 80 radiograms.
Is there a way to shorten it?
Use arrays of objects (like all the radio buttons, for instance) and iterate over them. Start like this:
var opts = [],
numOpts = 80;
for (var i=0; i<numOpts, i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
Edit: let's have a go at the full function. The only thing I'm not 100% sure about is whether you mean to use opX[i].checked or opX.options[i].selected (since your code does different things for op1 and op2/3). Shouldn't be too hard to extrapolate if I've guessed wrong, though.
function calc()
{
var opts = [],
numOpts = 80,
value = 0,
result = document.getElementById('result'),
i, j, opt;
for (i=0; i<numOpts; i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
numOpts = opts.length;
for (i=0; i<numOpts; i++)
{
opt = opts[i];
for (j=0; j<opt.length; j++)
{
// or did you mean:
// if (opt.options[j].selected) ?
if (opt[j].checked)
{
value = value + parseInt(opt[j].value, 10);
}
}
}
result.value = value;
return false;
}
jQuery is a great library that's like using JavaScript on steroids. It is well worth learning and there are plenty of examples out in the wild.
You can write complex "selectors" quite like this:
$('input[name=form[radio1]]').attr('checked').each(function() {
result.value = $(this).attr('value')
})
(I'm not sure if it will accept a name like "form[radio1]" as valid, but give it a try.

Categories

Resources