Calculations from checkboxes - javascript

This is for an Acrobat order form we use at work to calculate the amount of paper needed to print jobs. There are 4 conditions (saddle stitched books, perfect bound books single and double sided, and not books). All use a different formula to calculate paper quantity. I have all the formulas woking as individual programs but am having trouble getting them all together in the order form. My original thought was to put them all into the output field as a long if else statement. Then it occurred to me that I could run them from the checkbox.
Does either of these methods make more sense?
How do I run them from a checkbox and output the answer to field "PaperQty"?
This is the code for saddle stitched books. I want this to run when SS_CB checkbox is checked and the result to show in "PaperQty" field.
// get field values;
var FieldA = this.getField("Qty2").value;
var FieldB = this.getField("NoUp2").value;
var FieldC = this.getField("PageCount2").value;
event.value = ""; // default result;
// test for non-zero divisor;
if(Number(FieldB) != 0) {
event.value = (FieldC * FieldA / 4) / FieldB; // perform division;
event.value = Math.ceil(event.value); // Round up to next larger intiger;
}

Related

How to keep value from re-calculating when you go back in browser?

I have a multi-page form for making reservations which calculates the number of transportation services required based on a few factors. You first choose a number of passengers ('#input_2_6') and Depending on the type of vehicle you choose is how many vehicles you will need, so when you choose a vehicle the "Quantity" field ("#input_2_20") is updated. The on the next page/step, you have to choose if you want a one-way or round trip, so when you choose round trip, the Quantity field is multiplied by two. Then on the next page/step, you are just shown the summary of your order (confirmation page).
The problem is, with the current code, if you are on the confirmation page and decide to go back to the previous page to change something (perhaps you decided you don't want the round trip and only need one-way), the quantity number keeps the new value and now it is multiplied by 2 again when choosing round trip.
jQuery(document).ready(function ($) {
var totalBook;
$('#input_2_12').change(function () {
switch ($(this).val()) {
case 'Escalade|49':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 5);
$("#input_2_20").val(totalBook);
break;
case 'Suburban|0':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 6);
$("#input_2_20").val(totalBook);
break;
case 'Van|14':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 10);
$("#input_2_20").val(totalBook);
break;
}
});
totalBookNew = $("#input_2_20").val();
$('input:radio[name="input_7"]').change(function () {
$('#input_2_20').val(totalBookNew);
if ($(this).val() == 'Round trip'){
$('#input_2_20').val(totalBookNew);
newTotal = totalBookNew * 2;
$('#input_2_20').val(newTotal);
}
else if ($(this).val() == 'One way'){
$('#input_2_20').val(totalBookNew);
}
});
});
I've tried using the value of 'totalBook' from the first function on the second function but it returns undefined, that's why I created totalBookNew...
I really appreciate any help!
Looks like the main issue is after you do the calculations you set the calculated value into the original input field. Your best bet would be to store the calculations elsewhere in hidden html inputs. So you would have an input called something like:
<input type="hidden" id="input_2_20_calculated" value=0>
Then instead of setting the calculated value back into the input set it in the hidden input instead. Hidden inputs will get passed along with the form, so you would be able to use the calculated values. This is why you get the duplication is because every time the calculation is triggered it's doubling the previous calculated value.
totalBookNew = $("#input_2_20").val();
$('input:radio[name="input_7"]').change(function () {
$('#input_2_20').val(totalBookNew); //This line can be deleted
if ($(this).val() == 'Round trip'){
$('#input_2_20').val(totalBookNew); //You can also delete this line
newTotal = totalBookNew * 2;
$('#input_2_20_calculated').val(newTotal);
}
else if ($(this).val() == 'One way'){
$('#input_2_20_calculated').val(totalBookNew);
}
});
As a cautionary side note you should recalculate on the backend. Don't calculate in the front end and trust those calculations on the back end. It's easy to manipulate the form data on submit and post fake numbers.

jQuery calculation updating one row at a time

So, I'm trying to create a small table for working out the potential winnings of betting on a rubber duck race when each duck has certain odds.
I sort of have this working but have hit a stumbling block...
When the page loads all of the maths is done correctly based on the default value of £10. What I then want to do is allow people to change the amount of money they would like to bet per duck and the potential winnings for that duck only updates automatically.
This is what I have so far:
function calculate_odds(row) {
var winnings = 0;
// Set winnings to 0
var odds = $(row).find('#theodds').attr('data-duckodds'),
// Find the value of the data attribute for a specific td
betting_amount = $('[name="betting-amount"]').val(),
// Find the value entered into an input field
winnings = (parseFloat(odds) / 1 + 1) * betting_amount;
// Work out the winnings based on the odds given.
// Divide first number by 1 as all odds are something to 1 for now, then +1
// Multiply that number by the bet
// For example Bet 30 on 3/1 odds
// 3 / 1 = 3 + 1 = 4 * 30 = 120
$(row).find('.js-winnings').html(winnings.toFixed(2));
// Show the winnings amount in the final td in each row
}
$(document).ready(function() {
$('.lineup tbody tr').each(function() {
// Run the function calculate_odds() initially based on the default value;
calculate_odds();
$(this).find('[name="betting-amount"]').on('keyup', function() {
// Now loop through each row and change the winnings amount if the betting amount is changed
calculate_odds($(this).closest('tr'));
}).trigger('keyup');
})
});
From what I understand (my jQuery is not great), within this line: $(this).find('[name="betting-amount"]').on('keyup', function() { all I should need to do is select the specific row I want to update. Which should be simple right?
Instead what this does is takes the updated value from the first row and then applies as that as you change the later rows.
Can anyone point our where I'm going wrong? You can see the calculator here: http://www.kb-client-area.co.uk/ducks/races/race-1/
Thanks in advance :)
The specific problem you're encountering is where you're setting betting_amount:
betting_amount = $('[name="betting-amount"]').val()
You're looking globally in the document, and so finding the first instance.
Switching it to this makes it work:
betting_amount = $(row).find('[name="betting-amount"]').val()
As an aside: it would be better to use a class instead of an ID for #theodds, as IDs are supposed to be unique per document :)
I think perhaps your 'this' isn't referring to what you think it is in this line: calculate_odds($(this).closest('tr'));
Could you try something along the lines of:
$(this).find('[name="betting-amount"]').on('keyup', function(e) {
// Now loop through each row and change the winnings amount if the betting amount is changed
calculate_odds($(e.target).closest('tr'));
}).trigger('keyup');
})
As I said earlier, element IDs must be unique in a given document. You have the id theodds repeated as many times as the number of rows in your table which makes your HTML invalid! Remove those IDs and you could just work around the data-* that you already have.
function calculate_odds(row) {
row = $(row);
var winnings = 0,
//find the data-* from within the context of the keyup - the row
odds = row.find('[data-duckodds]').attr('data-duckodds'),
//find the entered amount from within the context of the keyup - the row
betting_amount = row.find('[name="betting-amount"]').val(),
//Your math
winnings = (parseFloat(odds) / 1 + 1) * betting_amount;
row.find('.js-winnings').html(winnings.toFixed(2));
}
$(document).ready(function() {
//You don't need an each loop here as the keyup will be triggered on every amount box on load as well.
$('.lineup').on("keyup", "[name='betting-amount']", function() {
calculate_odds($(this).closest('tr'));
})
.find("[name='betting-amount']").keyup();
});
Take a look at this fiddle for a demo.

Acrobat PDF calculation with checkbox

I've created a PDF form to help create an estimate for plumbing work. There are various lines that the contractor fills in for quanity, cost of the item and then automatically calculates the price for that line; this works fine.
But now I want to add a checkbox to the line that the customer would check if they actually want that work to be done. If they check the box then the price would appear in the final field, otherwise it would display 0.
My fields are:
QtyRow2 ItemCostRow2 CheckboxRow2 PriceRow2
I've tried this Javascript code in the Calculation tab for the PriceRow2 field, but it displays "0" in the price field whether the checkbox is checked or not.
var oFldQty = this.getField("QtyRow2");
var oFldItem = this.getField("ItemCostRow2");
if (this.getField("CheckboxRow2").isBoxChecked(0)) {
nSubTotal = oFldQty.value * oFldItem.value;
} else {
nSubTotal = 0;
}
event.value = nSubTotal;
How should I modify this to get it to work?
If this is the whole code in the calculation, it would be way safer to define nSubTotal; otherwise, it gets defined as a global variable, and can behave strangely.
Also, whenever this calculation runs, and the test results to false, nSubTotal is set to 0. That means, you have to define nSubTotal, and then add to it while you work through the form.
If you want to simply have a result in the field, there is no need to do the detour via a variable; you can set event.value in the true and the false path.
For a single checkbox, it is IMHO easier to use its value (or its "unchecked" value for portability of the code reasons). This leads to the following code snippet:
if (this.getField("CheckboxRow").value != "Off") {
// box is checked
event.value = oFldQtyty.value * oFldItem.value ;
} else {
// box is unchecked
event.value = 0 ;
}
And that should do it.
However, as you have a table, it is best practice to consolidate all calculations into one single script, which can be attached to a hidden read-only field which is not even involved in the calculation itself. This gives you much better overview and control over the calculation, and prevents calculation order errors.

How to use if statements inside a while loop

I'm very novice at programming and haven't had any luck in finding a tutorial useful for what I want to do.
I am creating a form that will have 2 drop down selections and then one input box which will produce a price depending on the 2 selections.
For the first drop down it will be a type of event. The second will be a selection of adult, child, or student (each selection has its own set ID). Then I want to produce prices dynamically that will appear in a text box based on the user's selections so something sort of like the following (I'm still figuring out JavaScript so bear with me this will be a poor example):
while eventid == 2
{
if registration == adult;
price == 45;
}
Any help would be appreciated.
I agree with the comments that you need to nail down basics - about what you are trying to do and JavaScript itself.
Having said this and based on what you have described, however, I do not think that you need a loop at all. The event type does not sound like a temporal condition for a repeated series of actions until it changes - the classic criteria for a loop.
It sounds like what you need is more like this:
if (eventid == 2) {
if (registration == 'adult') {
price = 45;
} else if (registration == 'child') {
price = 15; // or whatever
}// else if... // more registration conditions
} else if (eventid == 3) { // or whatever
if (registration == 'adult') {
price = 55; // or whatever
} else if (registration == 'child') {
price = 20; // or whatever
}// else if... // more registration conditions
}// else if... // more eventid conditions
I don't think you want a loop, I think the logic that you are looking for is just the if statement, as in "if the registration is an adult, and the event id is 2, then set the price equal to 45" so:
if(eventid == 2){
if(registration == 'adult')
price = 45;
if(registration == 'child')
price = 35;
}
Depending on what you want to do, there could be any number of combinations of logical structures you might employ. A switch statement comes to mind if you have a lot of event ids.

Set Text/Val not appearing in Text Input until clicked/focus (jQuery)

I have a checkbox which updates totals on a page based on whether it's checked or unchecked. On one part of my form, I would like to zero out a Telerik Numeric TextBox (Text Input field) if the user decides they do not require that category.
When the above checkbox is unchecked, the value in the textbox on the right should change back to zero. To accomplish this, I've written the jQuery code below (note, this function is called whenever something changes on the form):
var zeroValue = getNum(0.00);
//Scaffolding
if ($("#ScaffoldingRequired").attr('checked')) {
scaffoldingCost = getNum($("#ScaffoldingCost").val());
totalCost += scaffoldingCost;
} else {
$("#ScaffoldingCost").val(zeroValue);
$("#ScaffoldingCost").text(zeroValue);
}
//Round&Convert to 'decimal'
function getNum(num) {
var number = parseFloat(num) || 0.00;
var rNumber = Math.round(number * 100) / 100;
return rNumber.toFixed(2) * 1;
}
NOTE: To make sure everything rounds properly and doesn't give me NaN's, I've used my getNum function ( I understand it's a bit hack ).
This code works, and all my totals calculate properly but the textbox does not display a zero value until the user actually clicks on the input box. I've displayed this below:
Is there something I can do to recycle my input box so it displays the zero value immediately? Or am I setting the value/text completely wrong?
You say you're using Telerik, have you considered using their client API for changing the value of the textbox?
var textBox = $('#ScaffoldingCost').data('tTextBox');
textBox.value(0);

Categories

Resources