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>
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>
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>
If I have few on my form. How can I access to input what I need?
<label> First </label>
<input type="number" value="1" min="1">
<label>22</label>
<span>There I need value in input * val in label</span>
<label> Second </label>
<input type="number" value="1" min="1">
<label>12</label>
<span>There I need value in input * val in label</span>
................................
How can I do this? Maybe I need to use loop?
Not sure exactly which input you are trying to access.
You can use document.querySelectorAll("input[type=number]").
It will return an array with all inputs of type "number". Iterate through them to get what you need
You can use for loop to loop all inputs and addEventListener to run function on input change. Then just calculate value for each input and add to span as textContent.
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('change', function() {
var val = this.value * Number(this.nextElementSibling.textContent);
this.nextElementSibling.nextElementSibling.textContent = val;
})
}
<label>First</label>
<input type="number" value="1" min="1">
<label>22</label>
<span>There I need value in input * val in label</span>
<label>Second</label>
<input type="number" value="1" min="1">
<label>12</label>
<span>There I need value in input * val in label</span>
If you want to add values to spans even before input change you can add this part of code to previous one.
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
var val = inputs[i].value * Number(inputs[i].nextElementSibling.textContent);
inputs[i].nextElementSibling.nextElementSibling.textContent = val;
inputs[i].addEventListener('change', function() {
var val = this.value * Number(this.nextElementSibling.textContent);
this.nextElementSibling.nextElementSibling.textContent = val;
})
}
<label>First</label>
<input type="number" value="1" min="1">
<label>22</label>
<span>There I need value in input * val in label</span>
<label>Second</label>
<input type="number" value="1" min="1">
<label>12</label>
<span>There I need value in input * val in label</span>
You can add an id to the controls and then access it using jquery by the id.
<label> First </label>
<input type="number" value="1" min="1" id="input1">
<label id="label1">22</label>
<span id="span1">There I need value in input * val in label</span>
<label> Second </label>
<input type="number" value="1" min="1" id="input2">
<label id="label2">12</label>
<span id="span2">There I need value in input * val in label</span>
Then on your dcoument.ready just calculate it like this:
$( document ).ready(function() {
var result1=$(#input1).val()*$(#label1).val();
$('#span1').val(result1);
var result2=$(#input2).val()*$(#label2).val();
$('#span1').val(result2);
});
After you gave an id to the controls you can do it even nicer, looping through all the inputs an dynamically multiply them:
var i=0;
$("#myForm input[type=text]").each(function() {
i=i+1;
$('#span'+i).val($('#input'+i)*('#label'+i));
});
<p>
<label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
<input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<input type="checkbox" id="printed"/>Please tick if you would like a printed version<br />
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>
I would like a piece of javascript so that upon the checkbox being checked, it makes the postage value 3.50. However, it is 3.50 per copy of the complete ebook. So it would have to check the value of number box and times it by the value inside.
Solution that changes based on checkbox state:
var chap7 = document.getElementById('chap7'),
post = document.getElementById('post'),
printed = document.getElementById('printed');
printed.addEventListener('change', function() {
var quantity = parseInt(chap7.value, 10);
post.value = printed.checked ? quantity * 3.5 : quantity;
}, false);
chap7.addEventListener('change', function() {
post.value = parseInt(this.value, 10);
});
<p>
<label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
<input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<input type="checkbox" id="printed"/>Please tick if you would like a printed version<br />
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>
Solution that changes based on text input state:
var chap7 = document.getElementById('chap7'),
post = document.getElementById('post');
chap7.addEventListener('change', function(e) {
var quantity = parseInt(chap7.value, 10);
post.value = quantity * 3.5;
}, false);
<p>
<label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
<input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>