I have made a script that gets a number based on checked checkboxes, then there is a input where users can input a number which then gets calculated with my total numbers that I got from checkboxes. So my issue is that the total number doesn't gets updated when I uncheck/check checkbox again, and I need it to automatically update.
// Total Price Calculator
function calc() {
var tots = 0;
$(".checks:checked").each(function() {
var price = $(this).attr("data-price");
tots += parseFloat(price);
});
$("#no-text").keyup(function() {
var value = parseFloat($(this).val());
$('#tots').text(value*tots.toFixed(2));
});
}
$(function() {
$(document).on("change", ".checks", calc);
calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="number" id="no-text" placeholder="10">
<span id="tots">0.00</span>
So I need all of this to be done automatically, if I check 1st and 2nd checkbox and set input to number 5 it will calculate the price, then if I uncheck one checkbox it should update the price automatically according to already inputted number without need to update it again.
Thanks!
You can have multiple elements in one event handler, so include #no-text so that they'll both fire the calc event when either the checkbox or the input is updated
Then move $('#tots').text((number * tots).toFixed(2)) out of the old event listener, and add another variable to fetch the value of the input element
// Total Price Calculator
function calc() {
// Get value from input
let number = parseFloat($('#no-text').val() || 0);
let tots = 0;
// Add Checkbox values
$(".checks:checked").each(function() {
tots += $(this).data("price");
});
// Update with new Number
$('#tots').text((number * tots).toFixed(2));
}
$(function() {
$(document).on('change', '.checks, #no-text', calc);
calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="checkbox" class="checks" data-price="10">
<input type="number" class="duration-input" id="no-text" placeholder="10">
<span id="tots">0.00</span>
Related
I wanted to make multiple checkboxes and every time I check one of them the value of the first input reduce by a number for example when we select checkbox1 the number in input reduces by 10 and when we select checkbox2 it reduces by 20 and when we select both of them it reduces by 30.
I have handled the first checkbox though.
<html lang="en">
<head>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()" id="checkboxId">
<input type="checkbox" onclick="" id="checkboxId2">
<p id="par">hello</p>
<script>
function one () {
var check = document.getElementById("checkboxId");
if (check.checked) {
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
} else {
document.getElementById("par").innerHTML=document.getElementById("input").value;
}
}
</script>
</body>
</html>
You can try using data-* attribute. Also, you can get the value only from the checked check boxes, sum them and deduct that from the input value.
Try the following way:
function one () {
var total = Array.from(document.querySelectorAll(':checked'))
.map(el => el.getAttribute('data-value'))
.reduce((a,c) => a+ Number(c), 0);
document.getElementById("par").textContent = Number(document.getElementById("input").value) - total;
}
<input type="number" id="input">
<input type="checkbox" onclick="one()" data-value="10" id="checkboxId">
<input type="checkbox" onclick="one()" data-value="20" id="checkboxId2">
<p id="par">hello</p>
I have a non-clickable textbox that I am using to keep a running total (everytime a checkbox is clicked, it's value is being added to the textbox).
I am struggling however with doing some multiplication on this textbox value. I have a checkbox that, when selected, I would like to multiply by 0.9 (to simulate a 10% discount). How would I go about doing this?
Here's what I have so far (but is not working - textbox value just goes to 0.00):
$(document).ready(function($) {
var sum = 0;
$('input[id=10percent]').click(function() {
sum = 0;
$('input[id=15percent]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum * 0.9;
});
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="runningtotal">
Running CPC Total (in £): <input id='sum' type='text' readonly />
</div>
HTML (for radio boxes):
<div class="agencydiscount">
<h1>Agency Discount</h1>
<input type="radio" name="percentdiscount" value="0.00">None<br>
<input type="radio" name="percentdiscount" id="10percent" value="0.00">10% Discount<br>
<input type="radio" name="percentdiscount" id="15percent" value="0.00">15% Discount<br>
</div>
jQuery:
jQuery to update running total textbox:
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum += val;
});
$('#sum').val(sum.toFixed(2));
});
});
Your JS seems a little confused. You're attaching only one event handler and trying to loop over an unrelated selector that contains only a single element. You're also multiplying the value but not assigning the result to anything.
To make this work you need to attach the event handler to all the radio buttons. Then you can use the value property of all the radios to hold the number to multiply the #sum by to get the discounted total.
Also note that you need somewhere to store the original total, ie. the value before any discount is applied, so that the calculation always works from the base figure. You can use a data attribute for this, but note that you must update this attribute along with the value.
With all that said, try this:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" value="10.00">
£10.00
</label>
<label>
<input type="checkbox" value="5.00">
£5.00
</label>
<label>
<input type="checkbox" value="19.99">
£19.99
</label>
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
</div>
<div class="agencydiscount">
<h1>Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9">
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85">
15% Discount
</label>
</div>
As an aside, I would suggest researching the basics of JS as there's some fundamental principles you need to get a firm grasp of. This MDN guide is a great starter.
You must use their name instead of using their id. So your code must be like this:
$(document).ready(function($) {
$('input[type=radio]').on('change', function() {
var sum = $('input[name=percentdiscount]:checked').attr('value') * 0.9;
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="runningtotal">
Running CPC Total (in £): <input id='sum' type='text' readonly />
</div>
<div class="agencydiscount">
<h1>Agency Discount</h1>
<input type="radio" name="percentdiscount" value="0.00">None<br>
<input type="radio" name="percentdiscount" id="10percent" value="10.00">10% Discount<br>
<input type="radio" name="percentdiscount" id="15percent" value="20.00">15% Discount<br>
</div>
Why my codes is not getting the total value of each row?, its getting only the first row value.
tried to insert it into .each function, but its not functioning
function calc_total()
{
total=0;
$('#po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
}
get the grand total of each rows.
You need to select your inputs differently so you can add their total. Id's must be unique so it won't let you .each a single element. If you give them each a class with the same name you can do it like this:
var total = 0;
$('.po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="4">
<input type="input" class="po_total_amount" value="90">
<input type="input" id="totalPrice">
i need sum of (every check box value X its textbox value)
<input name="33" value="280000" onclick="test(this);" type="checkbox">
<input id="33" style="width:20px;float: left; text-align: center" type="text">
example:
fist checkbox value = 20 X its textbox value = 10
second checkbox value = 5 X its textbox value = 2
my answer = 20*10 + 5*2 = 210 (ok)
also i need when checkbox value changes my answer change, without click.
const totalBox = document.getElementById("total")
document.querySelectorAll("input[type=text]").forEach((input) => input.addEventListener("input", calculate))
document.querySelectorAll("input[type=checkbox]").forEach((input) => input.addEventListener("change", calculate))
function calculate() {
const checkboxes = document.querySelectorAll("input[type=checkbox]")
let total = 0
for (let checkbox of checkboxes) {
if (checkbox.checked) {
total += Number(checkbox.value) * Number(document.getElementById(checkbox.name).value)
}
}
totalBox.textContent = total
}
calculate()
<input name="33" value="280000" type="checkbox" checked>
<input id="33" value="10" type="text">
<br/>
<input name="34" value="150000" type="checkbox">
<input id="34" value="15" type="text">
<h2>Total: <span id="total"></span></h2>
Here you go with the solution https://jsfiddle.net/yuhpbz47/
var total = 0;
$('button[type="submit"]').click(function(){
$('input[type="checkbox"]').each(function(){
if($(this).is(':checked')){
total += $(this).val() * (parseInt($(this).next().val()) || 0 );
}
});
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="10" />
<input type="text" />
<br/>
<input type="checkbox" value="20"/>
<input type="text" />
<button type="submit">
Submit
</button>
If they are always grouped by two you can simply take all inputs, multiply every pairs value and add it up:
var result = Array.from(document.getElementsByTagName("input")).reduce(function(result,el,i,arr){
return result+i%2?el.value*(arr[i-1].checked?arr[i-1].value:0):0;
},0);
for shure this can be executed inside an onchange handler.
http://jsbin.com/muvigedodu/edit?js
You are trying to achieve, when a check box is clicked a value is multiplied by the value of the input check box then for all check box give us the sum right? if so this below code which is well documented should help out with it
Observe the pattern i used to get the multiply value so it can be dynamic
Hope it helps.
$(document).ready(
function(){
/**
* this is used to update our view so you see what we are * doing currently now
*/
function updateView(value){
$("#view").html(value);
}
$(".sum").click(function(event){
//we get our value to multiply our value with
var multiply = $(this).attr("multiply");
var value = $(this).val();
//we multiply here
var answer = multiply*value;
//we sum up this value with the sum in the hidden fied if checked else substract
var sumField = $("#sum");
if($(this).is(':checked')){
sumField.val(Number(sumField.val())+answer);
}else{
sumField.val(Number(sumField.val())-answer);
}
//update our view
updateView(sumField.val());
});
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Check boxes
<br>
1. <input type="checkbox" value="10" multiply="20" class="sum"> value 10, multiply 20 <br>
2. <input type="checkbox" value="5" multiply="10" class="sum"> value 5, multiply 10 <br>
3. <input type="checkbox" value="3" multiply="5" class="sum"> value 3, multiply 5 <br>
<input type="hidden" value="0" id="sum">
value: <div id="view">
</div>
I'm trying to add the values of any checked checkbox to an input text field.
Here's my fiddle: http://jsfiddle.net/Lf6ky/
$(document).ready(function() {
$(":checkbox").on('click', function() {
if ($(':checkbox:checked')) {
var fields = $(":checkbox").val();
jQuery.each(fields, function(i, field) {
$('#field_results').val($('#field_results').val() + field.value + " ");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
In this example, I have 3 checkboxes, with the values 1,2,3. If I click on all these checkboxes, then the input field should look like this: 1 2 3
If I uncheck any of these checkboxes, then that corresponding value should disappear in the input field.
How do I do this?
I've stored the collection of check-boxes in a variable $checks, then attach the handler to this collection. Inside the event handler, I take the collection once again and filter (return) only the check-boxes that are checked.
map() returns a jQuery object containing the values of the checked check-boxes, get() converts it to a standard array. Join those values with a space and put 'em in the input.
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(" ");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
On click of a checkbox, loop through the checked inputs, append to a string then assign that to your text box:
$(document).ready(function() {
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + " ";
});
$("#field_results").val(output.trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
First issue is
if($(':checkbox:checked')) {
will always be true since it returns a jQuery object and an object is a truthy value. If you were to use the if, you want to check the length. aka if($(':checkbox:checked').length) {
Secondly
var fields = $(":checkbox").val();
returns only the first element's value and it returns any checkbox, not just the checked ones. You want to loop through $(':checkbox:checked')
One way to attack it is to use an each and an array.
$(":checkbox").on('change', function() {
var total = [];
$(':checkbox:checked').each( function(){ //find the checked checkboxes and loop through them
total.push(this.value); //add the values to the array
});
$('#field_results').val(total.join(" ")); //join the array
});
Problem
if($(':checkbox:checked')) will always be true
var fields = $(":checkbox").val(); Will give first checkbox value
You can try this.
$(document).ready(function() {
$(":checkbox").on('click', function() {
var fields = '';
$(":checkbox").each(function() {
if (this.checked) {
fields += $(this).val() + ' ';
}
});
$('#field_results').val($.trim(fields))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" />
<br>
<input type="checkbox" value="1">1
<br>
<input type="checkbox" value="2">2
<br>
<input type="checkbox" value="3">3