jquery if checked all sum x2 - javascript

I have some problem with sum
example:
if checkbox with id='sms' is checked total sum x2 else x1
<form>
<input onclick="clickCh(this)" type="checkbox" value="1.00"> $1.00<br>
<input onclick="clickCh(this)" type="checkbox" value="2.00"> $2.00<br>
<input id="sms" type="checkbox"> pay via sms<br>
<BR>
<input id="total" type="text" name="total">
</form>
</div>
<script>
var total = document.getElementById("total")
$('#sms').change(function(){
var rise = this.checked ? '2' : '1';
});
function clickCh(caller){
if(caller.checked){
add(caller)
} else {
subtract(caller)
}
}
function add(caller){
total.value = total.value*1 + caller.value*1 * rise
}
function subtract(caller){
total.value = total.value*1 - caller.value*1 * rise
}
</script>

rise's scope is only within this function:
$('#sms').change(function(){
var rise = this.checked ? '2' : '1';
});
Declare it outside then modify it:
var rise;
$('#sms').change(function(){
rise = this.checked ? 2 : 1;
});

Related

How to count 2 fields at the same time?

I have some input with 3 values - entrance price, extra (in percent), price
It calculates by the formula: input price * per percentage extra = price
Here is my code:
HTML
function sum() {
var txtFirstNumberValue = document.getElementById('enterence_price').value;
var txtSecondNumberValue = document.getElementById('extra').value;
var result = parseFloat(txtFirstNumberValue) / 100 * parseFloat(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('price').value = result.toFixed(2);
}
}
<label>Enterence Price<br></label>
<input type="text" id="enterence_price" onkeyup="sum();">
<br>
<label>extra%<br></label>
<input type="text" id="extra" value="120%" onkeyup="sum();">
<br>
<label>Price<br></label>
<input type="text" id="price" onkeyup="sum();">
<br>
Now I need when I change the value in the "Price" input - my extra value should change automatically, the entrance price should not change
This is second formula:
Extra price =(price/entrance price)*100%
Pass the this keyword into your function, so you can detect which input has been triggered.
function sum(el) {
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
let result;
if (el.id === "enterence_price" || el.id === "extra") {
result = parseFloat(entrPriceEl.value) / 100 * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "price") {
result = (priceEl.value / entrPriceEl.value) * 100;
if (!isNaN(result)) {
extraEl.value = result + "%";
}
}
}
<label>Enterence Price<br></label>
<input type="text" id="enterence_price" onkeyup="sum(this);">
<br>
<label>extra%<br></label>
<input type="text" id="extra" value="120%" onkeyup="sum(this);">
<br>
<label>Price<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>

My JavaScript isn't responding to my HTML and CSS properly (namely buttons and <form> tags)

I am currently working on a donate page for a site that I'm working on in my free time. It's been going smoothly up until last week when I encountered a problem. My JS isn't responding properly to my HTML and I can't fix it. Here's my HTML:
var donateAmount = document.getElementById("selectedAmount");
if (donateAmount.value == "amount0") {
var totalAmount = 0;
} else if (donateAmount.value == "amount1") {
var totalAmount = 10;
} else if (donateAmount.value == "amount2") {
var totalAmount = 50;
} else if (donateAmount.value == "amount3") {
var totalAmount = 100;
} else if (donateAmount.value == "amount4") {
var totalAmount = 500;
};
function donateIsPressed() {
if (totalAmount >= = 0) {
alert("Thank you for your donation of " + totalAmount "$!")
} else {
alert("You didn't select anything!")
};
};
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="amount0"> 0 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount1"> 10 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount2"> 50 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount3"> 100 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount4"> 500 Dollars </input>
</form>
<div onclick='donateIsPressed ();' class="donateButton" id="processDonation"> test donate button </div>
The HTML is pretty simple, there's a tag with multiple options, and a button that's supposed to start the transaction. What the JS is supposed to do is to check what option is selected, then set the "totalAmount" variable to whatever is selected. Then it's supposed to give an answer depending on what totalAmount's value is. However, none of it works, and I'm currently getting nowhere with fixing. So I would appreciate it if one of you guys could point me in the right direction
Thanks in advance.
Try this.
function donateIsPressed() {
var donateAmount = document.querySelector('input[name="donateRadio"]:checked');
if (donateAmount) {
if (donateAmount.value == "amount0") {
var totalAmount = 0;
} else if (donateAmount.value == "amount1") {
var totalAmount = 10;
} else if (donateAmount.value == "amount2") {
var totalAmount = 50;
} else if (donateAmount.value == "amount3") {
var totalAmount = 100;
} else if (donateAmount.value == "amount4") {
var totalAmount = 500;
};
}
if (totalAmount >= 0) {
alert("Thank you for your donation of " + totalAmount + "$!")
} else {
alert("You didn't select anything!")
};
};
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="amount0"> 0 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount1"> 10 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount2"> 50 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount3"> 100 Dollars </input> <br>
<input type="radio" name="donateRadio" value="amount4"> 500 Dollars </input>
</form>
<div onclick='donateIsPressed ();' class="donateButton" id="processDonation"> test donate button </div>
I tried to solve your problem :
First I changed buttons value
Then I implement this logic :
var donateAmount = document.getElementById("selectedAmount");
var totalAmount = -1
function donateIsPressed() {
var radios = donateAmount.elements["donateRadio"];
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) { // radio checked?
totalAmount = parseInt(radios[i].value); // if so, hold its value in val
break; // and break out of for loop
}
}
if (totalAmount >= 0) {
alert("Thank you for your donation of " + totalAmount + "$!")
} else {
alert("You didn't select anything!")
};
};
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="0"> 0 Dollars </input> <br>
<input type="radio" name="donateRadio" value="10"> 10 Dollars </input> <br>
<input type="radio" name="donateRadio" value="50"> 50 Dollars </input> <br>
<input type="radio" name="donateRadio" value="100"> 100 Dollars </input> <br>
<input type="radio" name="donateRadio" value="500"> 500 Dollars </input>
<div onclick='donateIsPressed ();' class="donateButton" id="processDonation"> test donate button </div>
</form>
//Globals
let procesDonation, selectedAmount;
const data = {amount0: 0, amount1: 10, amount2: 50, amount3: 100, amount4: 500};
//Setup
const setup = () => {
//Id's should be unique and so can be set gobal
processDonation = document.querySelector('#processDonation');
selectedAmount = document.querySelector('#selectedAmount');
processDonation.addEventListener('click', donateOnClick);
};
//Functions
const donateOnClick = (event) => {
if(selectedAmount == null) return;
const target = event.currentTarget;
if(target.nodeName == 'DIV') {
const selectedButton = selectedAmount.querySelector('[name="donateRadio"]:checked');
const key = selectedButton?.value;
const amount = getAmount(key);
donateMessage(amount);
}
};
const getAmount = (key) => {
if(data == null || key == null || !Object.keys(data).includes(key)) return;
return data[key] || 0;
}
const donateMessage = (amount) => {
if(amount == null) return;
const message = amount > 0 ? `Thank you for your donation of ${amount}$!"` : `You didn't select anything!`;
alert(message);
}
window.addEventListener('load', setup);
<form id="selectedAmount" name="selectedAmount">
<input type="radio" name="donateRadio" value="amount0" checked> <label>0 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount1"> <label>10 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount2"> <label>50 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount3"> <label>100 Dollars</label> <br>
<input type="radio" name="donateRadio" value="amount4"> <label>500 Dollars</label>
</form>
<div class="donateButton" id="processDonation"> test donate button </div>
var totalAmount = 0;
var donateAmount = document.getElementById("selectedAmount");
function donateIsPressed() {
if (donateAmount.value == "amount1") {
var totalAmount = 10;
} else if (donateAmount.value == "amount2") {
var totalAmount = 50;
} else if (donateAmount.value == "amount3") {
var totalAmount = 100;
} else if (donateAmount.value == "amount4") {
var totalAmount = 500;
};
if (totalAmount >= 0) { // extra = here, removed
alert("Thank you for your donation of " + totalAmount "$!")
} else {
alert("You didn't select anything!")
};
};

How to make auto calculate in dynamic multiple form?

function sum()
{
$(document).on('keyup', "*[data-field='unit'],*[data-field='unit_price']", function(e)
{
var unit = document.getElementById('unit').value;
var unitPrice = document.getElementById('unit_price').value;
var result = parseInt(unit) * parseInt(unitPrice);
if (!isNaN(result))
{
document.getElementById('amount').value = result;
}
});
}
p/s: this only function at normal form. but not dynamic form.
[edit ?]
$('#unit, #price').on('input',function()
{
let qty = parseInt($('#unit').val())
, price = parseFloat($('#price').val())
;
$('#amount').val((qty * price ? qty * price : 0).toFixed(2));
});
you can do this whit jQuery Plugin i write simple one
you can test it on this :
$.fn.sum = function(options) {
"use strict";
var self = this;
self.defaults = {
unit : '[data-field="unit"]',
unit_price : '[data-field="unit_price"]',
result : '[data-field="amount"]',
onCalculate : function(result){},
};
self.settings = $.extend({},self.defaults, options );
var unit_count = $(self).find('input'+self.settings.unit).length;
var unit_price_count = $(self).find('input'+self.settings.unit_price).length;
if(unit_count > 0 && unit_price_count > 0){
var unit, unit_price=0, result=0;
$($(self).find('input'+self.settings.unit_price)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
$($(self).find('input'+self.settings.unit)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
function sum(unit, unit_price){
var result = parseInt(unit) * parseInt(unit_price);
if (!isNaN(result)) {
return result;
}
}
}
}
$(document).ready(function(){
$('form').sum({
onCalculate: function(self, active, result){
$(active).closest('form').find(self.settings.result).val(result);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="fff33">
<legend>
two
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit22">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price22">
<input type="text" data-field="amount" disabled>
</form>
<br>
<br><br>
<form id="fff">
<legend>
one
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price">
<input type="text" data-field="amount" disabled>
</form>
<br><br>

How to calculate numbers (total) based on the checked checkboxes using jQuery?

I have a a few checkboxes on my page and each checkbox has a data-price attribute.
The data-price represents a price of an item.
I'm trying to calculate a total value based on the checked boxes that is checked and also make sure the deduct the value of the UN-CHECKED checkboxes from the total value.
So far I have done this:
https://jsfiddle.net/523q4n72/1/
The issue that I have is that when I add up the price, it works fine but when I uncheck a checkbox, the total value jumps to minus and it does some strange calculations.
To test it, just check the checkboxes and uncheck one or two of them to see the issue.
$(document).on("click", ".checks", function() {
if ($(this).prop('checked') == true) {
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(price) + Number(tots);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
} else if ($(this).prop('checked') == false) {
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(price) - Number(tots);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
DRY - Don't repeat yourself.
In this case Loop each checked checkbox.
I have extracted the function so we can call it when changed AND when loading in case a checkbox was already checked
function calc() {
var tots = 0;
$(".checks:checked").each(function() {
var price = $(this).attr("data-price");
tots += parseFloat(price);
});
$('#tots').text(tots.toFixed(2));
}
$(function() {
$(document).on("change", ".checks", calc);
calc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" checked name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
Alternative way of calling and initialising
$(".checks").on("change", calc).change();
Just change:
var setPrice = Number(price) - Number(tots);
to
var setPrice = Number(tots) - Number(price);
and it should work fine. The issue is occurring as you are trying to subtract the total price from the checked element price.
UPDATED FIDDLE
A better idea is to recalculate the total sum each time from the currently checked elements (instead of adding or subtracting based on the current element)
And it is better to target the change event instead of the click.
$(document).on("change", ".checks", function() {
var checked = $('.checks:checked'),
sum = checked.get().reduce(function(prev, item) {
return prev + parseFloat(item.getAttribute('data-price'));
}, 0);
$('#tots').text( sum.toFixed(2) );
});
Updated fiddle at https://jsfiddle.net/523q4n72/3/
You were subtracting the total from the number clicked. Line 19 should read
var setPrice = Number(tots) - Number(price);
rather than
var setPrice = Number(price) - Number(tots);
:)
You must change Number(price) - Number(tots) to Number(tots) - Number(price) to have the right equation.
You redeclare everything every time, why not declare outside of the conditions ?
var price = 0;
var tots = "";
var setPrice = 0;
var ffp = 0;
$( document ).on( "click", ".checks", function() {
if ($(this).prop('checked')==true){
price = $(this).attr("data-price");
tots = $('#tots').html();
setPrice = Number(price) + Number(tots);
ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
} else if ($(this).prop('checked')==false){
price = $(this).attr("data-price");
tots = $('#tots').html();
setPrice = Number(tots) - Number(price);
ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}
});
Here you go with a solution https://jsfiddle.net/523q4n72/5/
var total = 0;
$(document).on("click", ".checks", function() {
if ($(this).prop('checked') == true) {
total += Number($(this).data("price"));
} else if ($(this).prop('checked') == false) {
total -= Number($(this).data("price"));
}
$('#tots').text(Math.round(total * 100) / 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
Hope this will help you.
Honestly I would just approach it a different way then you have. When .checks is clicked, iterate over each checkbox and add the values of those checked (updated fiddle). It seems much easier to read, imo.
$( document ).on( "click", ".checks", function() {
//reset totals on each click
var total = 0;
//Add checked totals
$('.checks').each(function(){
if($(this).prop('checked') == true) total += $(this).data('price');
});
//Update new total
$('#tots').html(total.toFixed(2));
});
Instead of looking at the item that is (un)checked, loop the ones that are checked using the :checked selector.
It simplifies your code:
$('.checks').on('change', function() {
var total = 0;
$('.checks:checked').each(function() {
total += $(this).data('price');
});
$('#tots').text( total.toFixed(2) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
var setPrice = 0;
$( document ).on( "click", ".checks", function() {
if ($(this).prop('checked')==true){
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(price) + Number(tots);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}else if ($(this).prop('checked')==false){
var price = $(this).attr("data-price");
var tots = $('#tots').html();
var setPrice = Number(tots) - Number(price);
var ffp = Math.round(setPrice * 100) / 100;
$('#tots').text(ffp);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>£<span id="tots">0.00</span></h4>
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94
<input type="checkbox" name="something" class="checks" data-price="17.94">17.94

How to overcome undefined error in javascript

Here is my code. You can also find it at a jsfiddle.
<form name="myform" method="post" onsubmit="return arith()">
<center><table>
<tr><td><font face="verdana,arial" size=-1>Value 1 </font></td><td><input type = "text" id = "num1"></td></tr>
<tr><td><font face="verdana,arial" size=-1>Value 2 </font></td><td><input type = "text" id = "num2"></td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Addition" id="check1"/>Addition</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Subtraction" id="check2"/>Subtraction</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Multiplication" id="check3"/>Multiplication</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Division" id="check4"/>Division</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><font face="verdana,arial" size=-1><input type = "submit" value = "Submit"></font></td></tr>
</table></center>
</form>
<p id="demo"></p>
Javascript code:
<script>
var op;
function changeCheckBox(val) {
try {
var i;
var max = document.myform.check.length;
var count = 0;
op = val;
for (i = 0; i < max; i++) {
if (document.myform.check[i].checked === true) {
count++;
serNoChecked = i;
}
}
if (count === 1) {
for (i = 0; i < max; i++) {
if (document.myform.check[i].checked === false) {
document.myform.check[i].disabled = true;
}
}
} else if (count === 0) {
for (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);
}
}
function arith() {
var n1 = parseInt(document.getElementById('num1').value, 10);
var n2 = parseInt(document.getElementById('num2').value, 10);
var newVal1;
var newVal2;
var newVal3;
var newVal4;
if (op == "Addition") {
newVal1 = n1 + n2;
} else if (op == "Subtraction") {
newVal2 = n1 - n2;
} else if (op == "Multiplication") {
newVal3 = n1 * n2;
} else if (op == "Division") {
newVal4 = n1 / n2;
}
var demoP = document.getElementById("demo");
{
var html = "";
html += "Addition =" + newVal1 + "<br/>";
html += "Subtraction =" + newVal2 + "<br/>";
html += "Multiplication =" + newVal3 + "<br/>";
html += "Division =" + newVal4 + "<br/>";
demoP.innerHTML = html;
}
return false;
}
</script>
While running it, I am getting undefined error for all the four operations.
If the user enters the two values and if they click all the checkboxes, it should display all the outputs corresponding to the arithmetic operations. How to do that?
You're not calling changeCheckBox anywhere in your code thus, the op is never set. Maybe you meant to have onchange="changeCheckBox(this.value);" for every check box (with this change, your code seems to be working as expected)?
<form name="myform" method="post" onsubmit="return arith()">
<center><table>
<tr><td><font face="verdana,arial" size=-1>Value 1 </font></td><td><input type = "text" id = "num1"></td></tr>
<tr><td><font face="verdana,arial" size=-1>Value 2 </font></td><td><input type = "text" id = "num2"></td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Addition" id="check1" onchange="changeCheckBox(this.value);" />Addition</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Subtraction" id="check2" onchange="changeCheckBox(this.value);" />Subtraction</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Multiplication" id="check3" onchange="changeCheckBox(this.value);" />Multiplication</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><input type="checkbox" name="check" value="Division" id="check4" onchange="changeCheckBox(this.value);" />Division</td></tr>
<tr><td><font face="verdana,arial" size=-1></font></td><td><font face="verdana,arial" size=-1><input type = "submit" value = "Submit"></font></td></tr>
</table></center>
</form>
Hope this helps.

Categories