When checkbox is selected multiply textbox value by 0.9 - javascript

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>

Related

Multiplying a text input by selected radio button

Hi i am new to javascript and having some trouble.
I need my function to take the user input "recserv" and multiply it by the value of the selected radio button, as well as update if the value is changed or the radio button is changed.
Changing the radio buttons seems to work, but I get an error when the "recserv" value is changed.
Thank you for any help!
<script>
function yeartot(service) {
var recserv = parseFloat(document.getElementById('recserv').value);
document.getElementById("result").value = service*recserv;
}
</script>
<body>
<p>Select the frequency</p>
<input onclick="yeartot(this.value)" type="radio" name="service" value="11">Monthly<br>
<input onclick="yeartot(this.value)" type="radio" name="service" value="6" checked> Bi-Monthly<br><br>
Recurring Service Amount <input onchange="yeartot()" id="recserv" value=0><br/><br/>
Total for year <input type="text" id="result">
The reason why you are getting NaN is because in your #recserv element's inline JS, you are not passing any value into the function when calling it. Therefore, you are multiplying with undefined which gives you a NaN value.
A quick fix to your issue will simply be letting the method itself retrieve the checked value of your input, and removing the need to pass any arguments to it. This is, however, a quick fix and I would never recommend using inline JS: check the next example for a proper solution.
function yeartot() {
var recserv = +document.getElementById('recserv').value;
var checkedService = +document.querySelector('input[name="service"]:checked').value;
document.getElementById("result").value = checkedService * recserv;
}
<p>Select the frequency</p>
<input onclick="yeartot()" type="radio" name="service" value="11">Monthly<br>
<input onclick="yeartot()" type="radio" name="service" value="6" checked> Bi-Monthly<br><br> Recurring Service Amount <input onchange="yeartot()" id="recserv" value=0><br/><br/> Total for year <input type="text" id="result">
Proposed solution: I suggest that you:
Use .addEventListener to listen to changes to your input elements. You can use document.querySelectorAll([selector]) to select the inputs that you want to bind the oninput event listener to. The callback will simply invoke yeartot()
Invoke yeartot() at runtime, so that you get calculated values when the document is loaded.
function yeartot() {
var recserv = +document.getElementById('recserv').value;
var checkedService = +document.querySelector('input[name="service"]:checked').value;
document.getElementById("result").value = checkedService * recserv;
}
document.querySelectorAll('#recserv, input[name="service"]').forEach(function(el) {
el.addEventListener('change', function() {
yeartot();
});
});
// Also, might want to run the first round of computation onload
yeartot();
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly<br><br> Recurring Service Amount <input id="recserv" value=0><br/><br/> Total for year <input type="text" id="result">
simply this...
document.getElementById('my-form').addEventListener('input', function () {
this.result.textContent = parseFloat(this.recserv.value) * parseInt(this.service.value)
})
<form id="my-form" onsubmit="return false">
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly
<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly
<br><br>
Recurring Service Amount <input name="recserv" value="0">
<br /><br />
Total for year <output name="result"></output>
</form>
-- adding a form makes things easier if each entry (or output) has a name.
-- using a form element, you do not need to use any ID, and you do not need to see which radio button is checked, you directly take the selected value
-- and do not use a change event but use input event
const setup = () => {
const serviceInputs = document.querySelectorAll('input[name="service"]');
serviceInputs.forEach(e => e.addEventListener('click', yeartot));
const recserv = document.querySelector('#recserv');
recserv.addEventListener('change', yeartot);
}
const yeartot = (service) => {
const checkedInput = document.querySelector('input:checked');
const recserv = document.querySelector('#recserv');
const serviceNumber = parseFloat(checkedInput.value, 10);
const recservNumber = parseFloat(recserv.value, 10);
const result = document.querySelector('#result');
result.value = serviceNumber * recservNumber;
}
//load
window.addEventListener('load', setup);
<body>
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly<br><br>
Recurring Service Amount <input id="recserv" value="0"><br/><br/>
Total for year <input type="text" id="result">
</body>
yeartot method has a parameter and when you use yeartot() in onchange property of input cause undefined value in service parameter.undefined value is not a number and take error.
Change your script into this
<script>
const input = document.getElementById("recserv");
const result = document.getElementById("result");
function yeartot(service) {
const checkedService = document.querySelector(":checked");
var recserv = Number(document.getElementById("recserv").value);
document.getElementById("result").value =
Number(checkedService.value) * Number(input.value);
}
</script>

jquery - sum of all checkbox value * their unique textbox value

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>

Use another attribute instead of the input value to update total

basically the below code creates a order total in the id="total" span depending on which checkbox/radio buttons are selected. The total is changed by the value of the checkbox/radio buttons however i was wondering if there's any other way to change the total without using the inputs value because its needed in the next part of the form. Maybe another input attribute? I'm just not sure how to go about it.
All help will be greatly appreciated, thank you!
<form action="cart.php" method="post" name="builder">
<input checked="checked" type="radio" name="term" value="12" onclick='check_value(this, 1)' />
<input type="radio" name="term" value="24" onclick='check_value(this, 2)' />
<input type="radio" name="term" value="36" onclick='check_value(this, 3)' />
<input type="checkbox" name="cid[]" value="2" onclick='check_value(this, "")' />
<input type="checkbox" name="cid[]" value="3" onclick='check_value(this, "")' />
<input type="checkbox" name="cid[]" value="4" onclick='check_value(this, "")' />
Total Order: $<span id="total">36</span>
</form>
function check_value(curElem, id) {
// calculate Total
var total = 0;
var controls = document.getElementsByTagName('input');
for (var i = 0; i < controls.length; i++) {
if ((controls[i].type === 'radio' || controls[i].type === 'checkbox') && controls[i].checked) {
total = total + parseFloat(controls[i].value);
}
}
document.getElementById("total").innerHTML = total;
//alert("Total: " + total);
}
if you really want to use another attribute, use it
use an attribute of your choice, say nval and access it as controls[i].getAttribute("nval")
otherwise,
you can create plenty of hidden input fields in the page, for each checkbox to hold your value. and use these hidden fields to compute total.

jQuery & JavaScript Excercise: Adding Values On Condition

How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO

jQuery - Get the value of closest textbox and assign it into a variable

How can I get the value of the closest textbox and assign it into a variable? Then after getting the value, change the current value of that textbox by multiplying it by the value of previous textbox. I have three instances of divs with the same input elements so I think .closest() or .next() can help me. Here is a snippet of my code
HTML
<div class="box">
<b>1</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
<div class="box">
<b>2</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
<div class="box">
<b>3</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" value="10"/>
</div>
JS
$("input[name=quantity]").each(function(){
$(this).bind("change keyup", function(){
var q = $(this).val();
var p = parseFloat($(this).closest("input[name=price]").val()).toFixed(2);
var amount = q * p;
$(this).closest("input[name=price]").val(amount)
console.log(amount);
})
})
non working demo
http://jsfiddle.net/c6yfS/
Thank you for responses
/* NOTE */
The purpose of the checkbox is just to show that I have a checkbox in between the two elements concerned.
As mentioned by other posters, you can use .siblings as .closest searches up the DOM tree (i.e. parent elements). However there is also a logic error in your code as the price you retrieve is never the right per unit price if quantity is changed. You will need a separate unit price hidden value perhaps to facilitate this
Check out the updated code here: http://jsfiddle.net/c6yfS/1/
it's better to use data attribute in order to calculating correctly:
HTML:
<div class="box">
<b>1</b>
<input type="text" name="quantity" value="1"/>
<input type="checkbox" name="ignoreThisCheckbox" checked="checked"/>
<input type="text" name="price" data-value="10"/>
</div>
JS:
$('input[name=quantity]').on("change keyup", function(){
var q = 0;
var p = 0;
var amount = 0;
q = parseInt($(this).val(), 10);
p = parseInt($(this).siblings("input[name='price']").data('value'), 10);
amount = q * p;
if (amount) {
$(this).siblings("input[name='price']").val(amount)
console.log(amount);
} else {
$(this).siblings("input[name='price']").val('Please specify the quantity')
}
})
DEMO
.closest is used to find the closest element up the DOM tree. What you are looking for is siblings or next | prev.
http://api.jquery.com/siblings/
http://api.jquery.com/prev/
http://api.jquery.com/next/
So
$(this).siblings("input[name='price']").val(amount);
Edit
Here is the full working JS:
$("input[name=quantity]").each(function(){
$(this).bind("change keyup", function(){
var $thi,q,$p,p;
$thi = $(this);
q = $thi.val();
$p = $(this).siblings("input[name='price']");
p = parseFloat($p.val()).toFixed(2);
$p.val(q * p);
});
});
for clarity I've just add a total field
You can solve it with this code :
$("input[name=quantity], input[name=price]")
.each( function(){ $(this).on( {'keyup': function(){ var j0=$(this).nextAll("input[name=total]"); j0.val( j0.prevAll("input[name=quantity]").val() * j0.prevAll("input[name=price]").val() ) } } ) } );
Click here to see the working "Fiddle"

Categories

Resources