Can I put two 'if statements' in one function and how? - javascript

Can I put two if statements in myFunction() ?
How to add one more 'if' statement to the myFunction() ?
Basically i need to set values for each specific checkbox, multiply it to number entered in the textbox and the result goes to 'total'.
For example :
if ( checkbox : Name - is selected) {
/*Multiply the value of Name*/ 200 * myNumber /*the number entered in textbox*/
}
And like before, the result goes to total.
$(document).ready(function() {
document.getElementById("demo").innerHTML = 0;
$('label').click(function() {
$('.option:checked').each(function() {
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
updateTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
} else {
document.getElementById("demo").innerHTML = 0;
};
updateTotal();
}
function updateTotal(){
var total = 0;
var totalAmount = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
totalAmount = total + parseInt(document.getElementById("demo").innerHTML);
$('#total').html( totalAmount +' $');
}
and
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber" onkeyup="myFunction()">
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
I am here for any further questions.
Thanks in advance for any help.

I am not sure if this is what you’re trying to achieve or not. But I’ll just walk you through simple usage of if, if else and else statements in your case.
In “myFuction” if you want a logic to be computed over the existing variables “x”, then you can go ahead and add another “else if” statement with the condition that you like to achieve.
But let say you want to add the logic around if for a whole new variable, let say “y”, then go on add another set of if, if else and else statement for y after the else block of “x”
Hope this helps. It would really help though if you can try to ask a precise question.

Related

get the sum of two checkbox on check

hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>
var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>
You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>

How to sum two results in Javascript

I am new at this and I got stuck.
I want to sum the two results that I get with this code.
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber">
<button onclick="myFunction()">Sum</button>
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
My question is - how to sum the two results and display it in 'Total:' at the end.
And how to remove the 'Sum' button, so you can see the result from the textbox in realtime in 'Total:' ?
Thanks in advance for any help :)
Edit : I need the sum from text box and the checkbox. For example : if the user have entered '5' this number equals 5 * 97 = 485. So '5' + Name(200) should be equals to 685.
Try this. I have defined a new method to calculate total amount. Whenever the checkbox or textbox is changed, the total is updated.
$(document).ready(function() {
document.getElementById("demo").innerHTML = 0;
$('label').click(function() {
$('.option:checked').each(function() {
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
updateTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
} else {
document.getElementById("demo").innerHTML = 0;
};
updateTotal();
}
function updateTotal(){
var total = 0;
var totalAmount = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
totalAmount = total + parseInt(document.getElementById("demo").innerHTML);
$('#total').html( totalAmount +' $');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber" onkeyup="myFunction()">
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
Create a new element with ID totalHolder and inside both functions call a third function (e.g. showTotal()) to sum those values:
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
showTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
showTotal();
}
function showTotal(){
var result1= parseInt($('#total').html());
var result2= parseInt($('#demo').html());
$("#totalHolder").html(result1+result2);
}
In order to remove onClick from button, you just need to set a listener:
$(docuemnt).ready(function(){
$("#myNumber").change(function(){
//Call your function inside the listener
myFunction()
})
})
Not sure if this satisfies your issue, but you need to do a couple things.
You should wrap input fields within a form.
Why are you mixing vanilla JS and jQuery? Stick with one or the other.
You should not be afraid to modularize your application with various functions.
Move the element queries out of the processing functions, instead pass their values in.
You can toggle the class in one loop, see below.
/* jQuery plugins */
(function($) {
/** Checks-off one or more checkboxes in a list of elements. */
$.fn.check = function(checked) {
return this.each(function(index, item) {
if (checked) {
$(item).prop('checked', 'checked');
} else {
$(item).removeProp('checked');
}
});
};
})(jQuery);
$(document).ready(function() {
$('#myNumber').val(5); // Set value to 5.
$('.option').slice(0, 1).check(true); // Check the first checkbox.
$('label').on('click', handleUpdate); // Attach a 'click' listener for label
handleUpdate(); // Call the function.
});
function handleUpdate() {
var sum = sumValues();
var num = $('#myNumber').val();
var mult = getMultiplier(num);
var total = num * mult + sum;
$('#total').html(total.toFixed(2) + ' $');
$('#demo').html(mult);
}
function sumValues() {
var total = 0;
$('.option').each(function() {
var isChecked = $(this).is(':checked');
if (isChecked) total += parseInt($(this).val());
$(this).parent().toggleClass('checked', isChecked);
});
return total;
}
function getMultiplier(value) {
if (value < 5) {
return value;
}
switch (value) {
case 5:
case 6:
case 7:
return 97;
case 8:
case 9:
case 10:
return 87;
default:
return 82;
}
}
label {
display: block;
}
.checked {
background : gold !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="check-form">
<input type="number" id="myNumber">
<button onclick="handleUpdate(); return false;">Sum</button>
<p id="demo"></p>
<label><input type="checkbox" class="option" value="200" /> Name</label>
<label><input type="checkbox" class="option" value="300" /> Blah</label>
<label><input type="checkbox" class="option" value="400" /> XYZ</label>
<label><input type="checkbox" class="option" value="800" /> Something</label>
<label><input type="checkbox" class="option" value="1200" /> Item</label>
</form>
<br>Total :
<div id="total">0 $</div>

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>

Why is my JavaScript function not returning the checked array value?

In the following code, my alert() is returning 0 when it should be returning the checked box value. I need it to return the value in the designated array associated with the checkbox.
<!DOCTYPE html>
<html>
<head> <title> Program 4 Parallel Arrays </title>
<style type="text/css"></style>
<script type="text/javascript">
var priceArray = [45.25, 24.88, 32.35, 27.33,
34.85, 36.24, 85.33, 45.32];
var pageArray = [1098, 536, 500, 792, 912, 1224, 899, 504];
function funRun () {
var totalPages = 0;
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
alert("totalPages : " + totalPages);
}
function funRun1 () {
var subTotal = 0;
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
alert("subTotal : " + subTotal);
}
tax = (.06 * subTotal)
total= (subTotal + tax)
</script>
</head>
<body>
<form name="bookForm">
<input type="checkbox" name="books" value="Flanagan" />
JavaScript, the Definitive Guide: $45.25 <br>
<input type="checkbox" name="books" value="McFarland" />
JavaScript & JQuery: The Missing Manual: $24.88 <br>
<input type="checkbox" name="books" value="Morrison" />
Head First JavaScript: $32.35 <br>
<input type="checkbox" name="books" value="Wilton&McPeak" />
Beginning JavaScript: $27.33 <br>
<input type="checkbox" name="books" value="Quigley" />
JavaScript by Example: $34.85 <br>
<input type="checkbox" name="books" value="Goodman" />
JavaScript Bible: $36.24 <br>
<input type="checkbox" name="books" value="Gosselin" />
JavaScript: The Web Technologies Series: $85.33 <br>
<input type="checkbox" name="books" value="Suehring" />
JavaScript Step by Step: $45.32 <br>
<br>
<input type="button"
value="Calculate Total"
onclick="funRun();funRun1()"/>
<input type="reset"/>
<br>
<br>
<input type="text" name="totalPages"/>Total Pages<br>
<input type="text" name="subTotal"/>Subtotal<br>
<input type="text" name="tax"/>Tax<br>
<input type="text" name="total"/>Total</p>
</body>
</html>
The issue is at your for loop.
Use:
for(i=0; i<document.bookForm.books.length; i++) {
Instead of:
for(i=0; i<document.bookForm.books[i].length; i++) {
The reason is that you should not access the array element at the size definition.
Also, the following block is returning a ReferenceError since the subTotal variable was not defined out of the funRun1() function:
tax = (.06 * subTotal)
total= (subTotal + tax)
I would change your funRun() to this
function funRun () {
var inputs = document.forms[0].querySelectorAll('[name=books]');
var totalPages = 0;
for(i=0; i<inputs.length; i++) {
if(inputs[i].checked) {
totalPages = totalPages + pageArray[i];
}
}
alert("totalPages : " + totalPages);
}
Apply the same to funRun1() and you'll be fine.
Also, an error is raised in the console because of this
tax = (.06 * subTotal)
total= (subTotal + tax)
The reason is that your subTotal scope is only in funRun1()
I would even suggest putting your script just before the </body>
apart from the changes suggested by Zanon, take these two lines inside the function funrun1() -
tax = (.06 * subTotal)
total= (subTotal + tax)
Also, I would suggest you to call funrun1() from inside funrun() onclick event of the button.
The issue is that when you are indexing with i inside your for loop it is 0 at that time which means that your loop won't iterate at all. Therefore,
Change:
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
To:
for(i=0; i<document.bookForm.books.length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
and Change
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
To:
for(i=0; i<document.bookForm.books.length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
In addition, here is a working JS Fiddle for you.
https://jsfiddle.net/Kitchenfinks/5ovkdh2c/
Happy Coding!

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

Categories

Resources