I have a variable called "total" that I would like to assign a number (or price) to and then add to that number when certain options are selected or checked. Here is the code I have so far.
Here is the code that sets the initial value (base price) of the variable that will be added to. THIS CODE CURRENTLY WORKS.
$('input[name=trimlevel]').change(function(){
var total = 0;
if(document.getElementById('basetrim').checked==true) {
var total = 0;
var basetrim = 3550.00;
total = total + basetrim;
$('#myTotal').html('$' + total);
}else if(document.getElementById('upgrade').checked==true) {
var total = 0;
var upgrade = 2400.00;
total = total + upgrade;
$('#myTotal').html('$' + total);
}else {
$('#myTotal').html('$' + total);
}
});
Here is an example of the code used to "add to" the value of the variable. THIS IS NOT WORKING.
$('input[name=leather]').change(function(){
if(document.getElementById('leather).checked == true) {
var leather = 180.00;
total = total + leather;
$('#myTotal').html('$' + total);
}
});
Here is the HTML for reference
<div class="modelsel">
<h2>1. SELECT MODEL</h2> <br>
<label for="basetrim">BASE MODEL</label>
<input id="basetrim" type="radio" name="trimlevel" value="2400.00">
<label for="upgrade">UPGRADED MODEL</label>
<input id="upgrade" type="radio" name="trimlevel" value="3550.00">
</div>
<div class="inside">
<h2>3. BASE MODEL ADD-ONS</h2><br>
<input type="checkbox" value="180.00" id="leather" name="leather" />
<label for="leather">Leather Seat (+ $180.00)</label><br>
</div>
<div id="myTotal"></div>
I am relatively new to Javascript and have been struggling with this for hours. Any help is appreciated. Thanks in advance.
Only some modifications need to be made in order to get things to work:
First one, there's a typo here:
if(document.getElementById('leather).checked == true) {
You missed a ' so substitute it by:
if(document.getElementById('leather').checked == true) {
Second, define the var total out of the functions and make it available to all of them. If you have your methods in the ready function you can define total there. Also remove the definition of total inside the functions or you won't use the one who is defined in ready.
Third, when the user clicks the checkbox, you're always adding value (don't know if that's what you want). In this fiddle, I add or diminish the amount of total according to the state of the checkbox.
The solution is already in the comments. The context of the functions is different. You can either define total outside of the functions or use an object for your behavior.
var someObject = {};
inside your function you can write with the dot notation.
someObject.total = 10;
$('input[name=trimlevel]').change(function(){
var total = 0;
if($(this).checked==true)) {
total = total + $(this).val();
}
$('#myTotal').html('$' + total);
});
Consider writing a comprehensive named function which adds up everything that can possibly contribute to your total :
function calculate() {
var total = 0;
if(document.getElementById('basetrim').checked) {
total = total + 3550.00;
} else if(document.getElementById('upgrade').checked) {
total = total + 2400.00;
}
if(document.getElementById('leather').checked) {
total = total + 180.00;
}
// further additions here
// further additions here
// further additions here
$('#myTotal').html('$' + total);
});
Then attach that named function as the event handler wherever necessary :
$('input[name=trimlevel]').change(calculate);
$('input[name=leather]').change(calculate);
//further attachments of calculate as event handler here
//further attachments of calculate as event handler here
//further attachments of calculate as event handler here
Related
I am trying to do one task using javascript, i have two text boxes one is for total amount and second is for discount and i have value in total amount for example 100 and when i insert discount in discount text box that inserted discount must be subtract from total amount but when i remove that discount that value must be as previous i tried below but it substract value but when it removes discount it does not work please help. Thanks in advance.
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount.length>0) {
var total=gross-totalDiscount;
} else{
var total=gross;
}
$('input[name="total_gross_amount"]').val(total);
});
Try this one.
As #Chris G proposed in comments and I edited his fiddle(just an example how this could be done, but since the questioner did not provide all info, this is what we have done):
$(".form-basic input").on('input', function() {
var gross = $('input[name="total_gross_amount"]').val();
var totalDiscount = $('.grand-discount').val();
var total = gross - totalDiscount;
$('#total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-basic">
<input type="number" class="total_gross_amount" name="total_gross_amount">
<input type="number" class="grand-discount" name="grand-discount">
</form>
<p>Total: <span id="total"></span></p>
I think this solve your problem, the key is to take gross out of input event:
$(document).ready(function(){
var gross= $('input[name="total_gross_amount"]').val();
$(".form-basic .grand-discount").on('keyup', function () {
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
});
ful example here https://jsfiddle.net/wkj0jjvp/
if you want to update gross amount, you should set an event for gross and put inside the discount event.
I need to calculate the tax of total amount during onchange of quantity or price values.
Here is what I did:
function sum() {
var result1 = document.getElementById('result1').value;
var result2 = document.getElementById('result2').value;
var result3 = document.getElementById('result3').value;
var result4 = document.getElementById('result4').value;
var result5 = document.getElementById('result5').value;
var result6 = document.getElementById('result6').value;
var myResult = Number(result1) + Number(result2) + Number(result3) + Number(result4) + Number(result5) + Number(result6);
tax(myResult);
document.getElementById('sumvalue').value = myResult;
}
Here result1,2,3.. are sub total of items. Total amount is passed to the tax calculation.
function tax(tot) {
var taxval = document.getElementById('tax_val').value;
amt = (tot * taxval)/100 ;
document.getElementById('tax_amt').value = amt;
}
tax_amt is the Tax Amount final value. My requirement is: when I change the tax value, I need to run this same method.
Below element is the tax percentage holder. Whenever I change the value it must be frequently change the tax_total.
<input id="tax_val" type="number" value="15" oninput="tax(this_element_value)" >
In your case, I understand that you want realtime update of tax, when input is changed.
I would do something like this:
<input id="tax_val" type="number" value="15" oninput="onInputChanged(this)" >
function onInputChanged(elem) {
tax(elem.value);
}
First you can assign a class to all the elements variables (result1, result2, result3...) then add a event to this class like this:
$(".result").change(function () {
sum();
});
<div>
<input class="input-class" />
<input class="input-class" />
</div>
<script>
$('.input-class').on('change', function () {
/// here you need find input and there value then you can sum of these value.
});
</script>
check this. I think it helps you.
<form>
<input type="text" name="" value="">
</form>
//for loop used to calculate balance after payment(x) and interest
// the variable I want defined from the form input box
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
You could attach a pseudo class in your input element and then get the value inserted like below:
<input type="text" name="" value="" class="js-interest">
<script>
var ele = document.getElementsByClassName("js-interest")[0];
var value = parseFloat(ele.value);
</script>
You can try document.getElementById('input_id').value and then use parseInt to get it as an integer, as below:
var x = parseFloat(document.getElementsByName('number_box').value);
Also, the html must look something like this:
<form>
<input type="text" name="number_box" value="">
</form>
Optionally, instead of document.getElementsByName() you can use document.getElementById() or document.getElementsByClassName().
Update:
If I am not wrong
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
It seems like you are writing to the DOM inside a for loop don't do that calculate your ANS and then write to the DOM.
Also, don't read the data from input inside the loop. (You will be repeatedly reading and writing the data thats not good.)
Your for loop for(i = 6000; i>=10; i = i * (1+0.2/26)-x) is incrementing using some expression i = i * (1+0.2/26)-x (make sure it is bound to the condition and its not making the loop infinite)
You can select the value from the input field using the following code
x = parseInt(document.querySelector('form input[name="my_number"]').value);
document.querySelector it uses CSS style selector. So, to select the input field inside your form. I have added a name to the form as name="my_number"
<input type="text" name="my_number" value="">
now using the css selector form input[name="my_number"] it select the input field inside a form with name "my_number"
The whole Query selector that will return the input element is this,
document.querySelector('form input[name="my_number"]')
now to get the value of the input field you have to read the value property of the input field.
document.querySelector('form input[name="my_number"]').value
This will return your input value as string.
Now, we need to parse that string value to a Integer format.
We do that like this, (using parseInt)
parseInt(document.querySelector('form input[name="my_number"]').value)
I have added you code in a function named calc
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
I have fetched the answer from a function named get calculated answer and its good to do this way.
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
It is called when you submit the form.
To do that I have added onsubmit='calc()' on your form tag.
<form onsubmit='calc()'>
Additionally, I have added this function that submits the form when you have pressed enter too (Just for fun) :)
document.onkeydown=function(){
if(window.event.keyCode=='13'){
calc();
}
}
It just listens for key down press and check if it is a enter key (keycode is 13)
and calls the same calc function.
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
document.onkeydown = function() {
if (window.event.keyCode == '13') {
calc();
}
}
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
<form onsubmit='calc()'>
<input type="text" name="my_number" value="">
<input type="submit" id="submitbtn" />
</form>
I need to be able to add a percentage to the total price when a radio button is selected. The code currently works, but only adds a value to the radio button. I need that, but also need to take the total calculated price with addOns and + a percentage to it.
Does anyone know how I can change this with Jquery?
Thanks in advance.
Jsfiddle: http://jsfiddle.net/4bitlabs/mGLfk/5/
HTML:
<div class="price">Estimate Price $<label for="amount1" class="total">0</label></div>
<p class="itemdesc1">How many "Linear Feet" of boards do you have?</p>
<input id="amount1" class="amount" data-for="amount1" />
<div class="addon"><input id="amount2" type="checkbox" value="10.00" class="radio addOn" data-for="amount1" />Add Red $10.00</div>
<div class="addon"><input id="amount3" type="checkbox" value="20.00" class="radio addOn" data-for="amount1" />Add Blue + 20%</div>
Jquery:
$(function () {
$('.amount').keypress(function () {
changeAmount($(this));
});
$('.addOn').change(function () {
var $original = $('#' + $(this).data('for'));
changeAmount($original);
});
});
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
$('label[for=' + id + ']').text(amount.toFixed(0))
}
Ok, I would rewrite what I understand from your question, please, correct me if I'm wrong...
You have CHECKBOXES, and you have an input where you may write a number of items you want to purchase. Then, you want to know the final price of the items you purchase, applying some considerations depending on what CHECKBOX are clicked.
Well, that said, I'll start first assuring you always trigger an "adding function" when anything changes (let's say, you change the number of inputs, or you click a checkbox). You almost did it, but you pass a parameter and I think that is not necessary. When you'll trigger anytime the calculation, you'll always have the right result.
Other thing, you need to distinguish between "adding checkbox" (adds a price per item) and "percentage checkbox" (adds a percentage to the price), to know what value you have to add. Just add clases to your checkboxes to distinguish between them. I'll add a fiddle:
Changes:
The clasess in the checkboxes, to know what we want to do with any of them, put attention on the add and percentage clasess:
<div class="addon"><input id="amount2" type="checkbox" value="10.00" class="radio addOn add" data-for="amount1" />Add Red $10.00</div>
<div class="addon"><input id="amount3" type="checkbox" value="20.00" class="radio addOn percentage" data-for="amount1" />Add Blue + 20%</div>
Your function adding must be called anytime you change anything, to allow you know what is changed, and set price to zero when changing the value (optional).
$('.amount').keydown(function () {
$('.price label').text('0');
});
$('.amount').keyup(function () {
changeAmount();
});
$('input:checkbox').change(function () {
changeAmount();
});
And last, depending on the class of checkbox clicked, different calculation:
function changeAmount() {
var $amount = 0;
$amount = parseFloat( $('.amount').val() ) * 20;
if (isNaN($amount)) {
$amount = 0;
}
var $add = 0;
$('.add:checked').each(function () {
$add += parseFloat( $(this).val() );
});
// Calculate percentage of the Base product
if ( $('.percentage').is(":checked") ) {
$amount = $amount * (1 + $('.percentage').val()/100 );
}
var $total = parseFloat( $amount + $add );
$('.price label').text( $total.toFixed(0) )
}
The fiddle: http://jsfiddle.net/mGLfk/11/
Hope it likes you! XD
I think I got it http://jsfiddle.net/mGLfk/10/
First, use keyup instead of keypress. I added two separate class for percent and sum.
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.sum.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
var percentage=100;
$('.percent.radio:checked[data-for="' + id + '"]').each(function () {
percentage += parseFloat($(this).val());
});
amount*=(percentage/100);
$('label[for=' + id + ']').text(amount.toFixed(0))
}
Preamble: I'm more of a PHP/MySQL guy, just starting to dabble in javascript/jQuery, so please excuse this dumb newbie question. Couldn't figure it out from the Docs.
I have a form without a submit button. The goal is to allow the user to input values into several form fields and use jQuery to total them up on the bottom in a div. The form kinda looks like this but prettier:
<form>
Enter Value: <input class="addme" type="text" name="field1" size="1">
Enter Value: <input class="addme" type="text" name="field2" size="1">
Enter Value: <input class="addme" type="text" name="field3" size="1">
etc.....
<div>Result:<span id="result"></span></div>
</form>
Is it possible to add these up? And if so, can it be done anytime one of the input fields changes?
Thanks.
UPDATE:
Brian posted a cool collaborative sandbox so I edited the code to look more like what I have and it's here:
http://jsbin.com/orequ/
to edit go here:
http://jsbin.com/orequ/edit
Sticking this right after the </form> tag should do it:
<script>
function displayTotal() {
var sum = 0
var values = $('.addme').each(function(){
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#result').text(sum);
}
$('.addme').keyup(displayTotal);
</script>
Here's a demo: http://jsbin.com/iboqo (Editable via http://jsbin.com/iboqo/edit)
Any non numeric or blank values will be disregarded in the calculation (they'll be given a value of zero and hence not affect the sum).
function sumValues() {
var sum = 0;
$("input.addme").each(function(){
var $this = $(this);
var amount = parseInt($this.val(), 10);
sum += amount === "" || isNaN(amount)? 0 : amount;
});
$("#result").text(sum);
}
$(function() {
sumValues();
$("input.addme").keyup(function(){
sumValues();
});
});
Working Demo
(function(){
var context = $("form"), elements = $("input.addme", context);
function getSum(elements) {
var sum = 0;
$(elements, context).each( function() {
var v = parseInt(this.value);
v === parseInt(v,10) ? sum += v : sum = sum;
})
return sum;
}
$(elements).bind("keyup", function() {
$("#result").text( getSum(elements) );
});
})();
isolated scope and context, included dealing with non-integer values, function getSum should rather return a value than do something itself.
Try this:
$(".addme").bind("change",function(){
var _sum = 0;
$(".addme").each(function(i){
_sum += parseInt($(this).val());
});
$("#result").val(_sum);
});