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>
Related
I have a form where I calculate the price based on the checkboxes checked. But I am having trouble as its not updating the final price correctly. I did some jQuery coding but it's not functioning properly. How can I debug the code and fix it?
//Price Calculator
$(document).ready(function(){
function Calculator(){
let totalAmount = 0;
if($('input[datasource=service_0]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 395;
return totalAmount;
}else if($('input[datasource=service_1]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 392;
return totalAmount;
}else if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2) {
totalAmount = 397;
return totalAmount;
}
}
//Insert Updated Amount to Budget field
$("input[type=checkbox]").on("click", function(){
if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2){
$("input[name=wpcf-book-amount]").val(Calculator());
} else{
$("input[name=wpcf-book-amount]").val(Calculator());
}
})
})
<div class="extra-services">
<ul>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="5" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_0">
<label for="wpcf-additional-services">Cot (EUR 5)</label>
</li>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="2" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_1">
<label for="wpcf-additional-services">BABY CHAIR (EUR 2)</label>
</li>
</ul>
<input type="text" name="wpcf-booking-amount" id="booking_field" placeholder="Booking Amount (System Generated)" readonly>
</div>
Form containing the fields responsible to calculate the booking amount
<html>
<head></head>
<body>
<input type="checkbox" id="1st" onclick="ge()" value=500>
<label for="1st"> I have a bike</label><br>
<input type="checkbox" id="2nd" onclick ="ye()" value=200>
<label for="2nd"> I have a car</label>
<input type="number" id="here" value="0">
<script>
var amt = 0;
var st = document.getElementById("1st");
var nd = document.getElementById("2nd");
var num = document.getElementById("here");
function ge() {
if(st.checked == true ){
var g = parseInt(st.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(st.value);
num.value = amt;
}
}
function ye() {
if(nd.checked == true){
var g = parseInt(nd.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(nd.value);
num.value = amt;
}
}
</script>
</body>
</html>
Here you go if it's only for two checkbox this will work, for live demo click here
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.
(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>
How to explode value from input type checkbox for auto sum in this code ?
....................................................................................................................................................................
<form id="form1">
<input type="checkbox" value="bgh_9.99" onclick="UpdateCost()">Game 1 ( 9.99)<br>
<input type="checkbox" value="ujh_19.99" onclick="UpdateCost()">Game 2 (19.99)<br>
<input type="checkbox" value="hhb_27.50" onclick="UpdateCost()">Game 3 (27.50)<br>
<input type="checkbox" value="uu_45.65" onclick="UpdateCost()">Game 4 (45.65)<br>
<input type="checkbox" value="jjhh_87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="checkbox" value="hhh_87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="text" id="totalcost" value="">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "";
}
}
return null;
}());
</script>
Easy way is to split() the checkbox value.
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
number = split_array[1]; // "9.99"
sum += parseFloat(number); // 9.99
I have created two input text fields by which the user have to give two values. Using javascript, I need to get those values perform addition, subtraction, multiplication and division based on the checkbox checked. How to do that?
Here is my code..
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS Assignment</title>
<script>
function changeCheckBox() {
try {
var max = document.myform.check.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == false) {
document.myform.check[i].disabled = true;
}
}
} else if (count == 0) {
for (var i = 0; i < max; i++) {
document.myform.check[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
} else if (count > 0) {
return false;
}
} catch (e) {
alert(e.message);
}
}
</script>
<script type="text/javascript">
function arith()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
x=num1 + num2;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x;
}
</script>
</head>
<body background="photo.jpg" onload="arith()">
<h3>Simple JavaScript Arithmetic Operations</h3>
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" value="check1" id="check1" onclick="changeCheckBox()">Addition<br>
<input type="checkbox" name="check" value="check2" id="check2" onclick="changeCheckBox()">Subtraction<br>
<input type="checkbox" name="check" value="check3" id="check3" onclick="changeCheckBox()">Multiplication<br>
<input type="checkbox" name="check" value="check4" id="check4" onclick="changeCheckBox()">Division<br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
</body>
</html>
Try sending the value of the HTML into the function, and then use those as an if statement check (or switch statement).
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" id="check1">Addition<br>
<input type="checkbox" name="check" id="check2">Subtraction<br>
<input type="checkbox" name="check" id="check3">Multiplication <br>
<input type="checkbox" name="check" id="check4">Division<br><br>
<input type="submit" value="Submit">
<p id="demo"></p>
Notice the value attributes now have unique value. And you're sending that into the function as a parameter.
Now just have a function that returns what you want
var newVal = "Unset";
var plus = document.getElementById("check1");
var minus = document.getElementById("check2");
var times = document.getElementById("check3");
var divide = document.getElementById("check4");
var demoP=document.getElementById("demo");
plus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1+n2;
demoP.innerHTML="x=" + newVal;
}
minus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1-n2;
demoP.innerHTML="x=" + newVal;
}
times.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1*n2;
demoP.innerHTML="x=" + newVal;
}
divide.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1/n2;
demoP.innerHTML="x=" + newVal;
}