Calculate the total of values in text boxes - javascript

I have a screen on my ASP.Net page, which, depending on a selection by the user, they get offered between 1 and 5 text boxes. These boxes allow the user to type in an amount.
When the user enters the screen, based on certain criteria, a certain number of these edit boxes are displayed. They are not hidden... if I want 3 boxes, then only 3 boxes are on the screen.
In javascript, as the user types in an amount, a 'Total' edit box is displayed, summing up the values from each box.
So, as the user types, the value in the total updates with the total calculated for all text boxes:
I use:
onkeyup="calculateTotal()"
on the editbox.
To do that, I use the code below:
function calculateTotal() {
var amt0 = $('.txtAmount0').val();
var amt1 = $('.txtAmount1').val();
var amt2 = $('.txtAmount2').val();
var amt3 = $('.txtAmount3').val();
var amt4 = $('.txtAmount4').val();
var amt = Number(amt0);
if (!isNaN(amt1))
amt += Number(amt1);
if (!isNaN(amt2))
amt += Number(amt2);
if (!isNaN(amt3))
amt += Number(amt3);
if (!isNaN(amt4))
amt += Number(amt4);
$('.txtTotalAmount').text('$' + amt);
}
The first issue is that it seems I am losing some precision in the calculation:
I am not sure why I am getting a strange rounding issue, when all I am doing is summing up.
Additionally, it seems a bit dirty, if I added more boxes, I need to modify the code.
Is there a better way for this code to work?

You can something like this:
var sum = 0;
$("input[class*='txtAmount']").each(function() {
if ($.isNumeric($(this).val()) ) {
sum += Number($(this).val());
}
});
$('.txtTotalAmount').text('$' + sum.toFixed(2));

Related

clear content in a text entry box with adobe captivate

I am making a simple math game in adobe captivate. When the slide loads two random numbers are generated. The user enters a sum in a text entry box and submits their answer. If the user's answer matches the correct sum they get a new problem.
All of this works, but I can't figure out how to clear their answer out of the text entry box when they submit it.
My code is below:
var sum = window.cpAPIInterface.getVariableValue('userAnswer');
var rand1 = window.cpAPIInterface.getVariableValue('rand1');
var rand2 = window.cpAPIInterface.getVariableValue('rand2');
var corrSum = rand1 + rand2;
if (sum == corrSum ) {
alert('great jobs');
var rand1 = Math.floor((Math.random() * 20) + 1);
var rand2 = Math.floor((Math.random() * 20) + 1);}
else {alert('try again'); }
It can be done using jQuery. Not sure what the instance names of your text entry boxes are, but say you have a TEB you've named "InputText", Captivate will then output a textfield with the ID of "InputText_inputfield". You can then access this text field and clear its contents with the following jQuery code:
$("#InputText_inputfield").val("");
If it's the first text field in a series and you want it to have focus, use the following jQuery code:
$("#InputText_inputfield").val("").focus();
It's as simple as adding the above code to the "Execute JavaScript" Script_Window, for your 'clear' button.

Troubleshooting jQuery input value

I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when click changes the amount to $5. I'm trying to get get it so that when the user changes the amount from 5 that it changes the amt = to user input.
The bit of script that changes it
function setDonrAmount(id){
var amt = id.substring(10);
if( amt == 'Other' ){ amt = 5}
var others = id.substring(0,10);
$("button[id*="+others+"]").removeClass('active');
$('button#'+id).addClass('active');
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp
I've made a few updates to setDonrAmount() to handle custom donations.
$("#donrAmountButtons").on("click", function() {
var amt = id.substring(10);
setDonrAmount(amt);
$('#donrAmount' + amt).addClass('active');
});
$("#donrAmountInput").on("focusout", function() {
setDonrAmount($("#donrAmountInput").val());
$('#otherAmount button').addClass('active');
});
function setDonrAmount(val) {
var amt = val || 0;
if (amt.length < 2 && amt < 5)
amt = 5;
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
$('#donrAmountButtons .active').removeClass('active');
}
You'll want to check for a keyup event on the input field, and make the selection when that happens. Something like... (inside document.ready)
$('#donrAmountInput').on('keyup', function() {
// Probably best to strip any non-numeric characters from the field here
amt = $(this).val();
// pseudo-code: $('#donrAmountOther').select(); as I'm not sure about jQuery's handling of input group buttons. There'll be a way to select this one somehow!
});

Totalling an ExtJS editable grid's input fields

This question regards ExtJS 3 editable grids. I have a need to total the input fields of one column of an editable grid. There is the store's sum method but sometimes the data in the input fields is not necessarily in the store; for instance you might make an entry in the input field and then click a button on the toolbar.
The "traditional" way in this case seems to be to set up the appropriate listener and commit the content of the input field to the store, but this can get convoluted and seems downright unnecessary if as a result of clicking the toolbar button you will ultimately get re-directed elsewhere anyway. Is there another solution?
An alternative is to gather up all the input fields using the oft-overlooked Ext.query functionality; the following does this for the second column of a grid ('.x-grid-col-0' would be the first column):
var qtyFields = Ext.query('.x-grid3-col-1 input', myGrid.getView().mainBody.dom);
var total = 0;
var qty;
for (var i=0, n=qtyFields.length; i<n; i++) {
qty = parseFloat(qtyFields[i].value);
total += isNaN(qty) ? 0 : qty;
}
An alternative that doesn't rely on knowing classnames in the HTML is to get the information from the editing plugin.
var fields = grid.findPlugin('rowediting').editor.form.getFields();
var total = 0;
for (var i=0, n=fields.getCount(); i<n; i++) {
var qty = parseFloat( fields.getAt(i).getValue() );
total += isNaN(qty) ? 0 : qty;
}

drop down menu updates inner HTML when changed, javascript

I have drop down menus, the last 2 are price and tickets which then makes a calculation and shows the total amount on screen when selected. It works fine although if i change the selection to a different price the total does not update. Also the same idea applies to the part where the user selects 4 or more tickets and an message appears on screen. Im sure its something simple but i cant seem to figure it out.
I have attached a Jsfiddle.
http://jsfiddle.net/Dwdqg/
function totalPrice(ticketCount,priceAmount)
{
if (tickets.selectedIndex != 0 && price.selectedIndex != 0) // if the price and tickets is not 0 or not selected
{
tickets.onchange = ticketCount; //when tickets is changed assign the index to var ticketCount
price.onchange = priceAmount;
var ticketCount = tickets.value; //get the value of ticketCount index
var priceAmount = price.value;
var totalPrice = (ticketCount * priceAmount);
document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);
}
if (ticketCount >= 4) // if ticketCount is 4 or more
{
totalPrice = totalPrice + 10; // add on 10 to the price
document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);
document.getElementById("moreTickets").innerHTML = ("Buying four or more tickets will add an additional £10 fee.")
}
}
You're not calling totalPrice in your change handlers.
For example:
price.onchange = function()
// totalPrice needs to be called
}
You've attached it here
<select name="tickets" id="tickets" onChange="totalPrice(tickets)" style="width:120px">
However, that only responds to changes to number of tickets. You haven't attached it to the other elements.
Also - your onchange only fires once because you're replacing the option fields using fillList after the change event fires. You can either reattach the handler or have it respond to a click event.
With that said - I don't recommend attaching handlers as HTML attributes and I suggest cleaning up your code to be more readable.

Updating Table Totals with Javascript

I recently added some functionality to a table using jQuery to allow users to add/delete table rows on the fly which is working well. However in doing so I broke the automatic calculation of totals based on the values enter into some cells in the table rows and for the life of me I can't work out how I broke it nor how to fix it.
I've also noticed that deleting a table row doesn't update the totals either (this was the new feature that I added).
Here's the script that runs that calculates the average number of hours per week for a single row - it should also update the total moderate or high field at the bottom of the table at the same time:
$(window).load(function(){
//Sum Table Cell and Map
$('#lastYear')
.on('change', 'select', calc)
.on('keyup', 'input', calc);
function calc(){
$('#lastYear tr:has(.risk)').each(function(i,v){
var $cel = $(v.cells);
var $risk = $cel.eq(1).find('option:selected').val();
var $numb = $cel.eq(2).find('input').val();
var $weeks = $cel.eq(3).find('input').val();
var $avg = ($numb * $weeks) / 52;
var $avgRounded = Math.round( $avg * 10 ) / 10;
$cel.eq(4).find('input').val($avgRounded);
});
var tot = {high:0,moderate:0};
$('#lastYear tr:has(.risk) option:selected')
.map(function(i){
var el = $(this).val();
var qty = parseFloat($('#lastYear tr:has(.risk)').eq(i).find('td:last').prev().find('input').val());
if (!tot.hasOwnProperty(el)) {
tot[el] = 0;
}
tot[el] += qty
return tot;
}).get();
// console.log(tot);
$('#textfield4').val(tot.moderate.toFixed(1));
$('#textfield5').val(tot.high.toFixed(1));
}
});//]]>
I've setup a jsFiddle that shows the current functionality - you can see if generates the averages but generates a 'NaN' result for the totals when entering data, and when you click the Delete button it should also update the totals too.
Update: I think problem is that the script is looking for the last table cell then going to the previous one to get the value. This used to work when the average cell was the 2nd last cell, but not it's the 3rd last cell and I don't know how to look for that cell by name/id etc. Any ideas?
I'm new to Javascript and have spent almost a day trying to work this out so really appreciate some assistance with this.
Working jsFiddle Demo
You have 2 td after your desired input. So you must call prev method twice:
var qty = parseFloat(
$('#lastYear tr:has(.risk)').eq(i).find('td:last')
.prev().prev() // call prev method twice
.find('input').val()
);
Mark your cells that store the average with eg a CSS class, than use that to find the cell within the row (rather than relying on td:last).
eg:
var row = $('#lastYear tr:has(.risk)').eq(i); // if this is the TR you want..
var avgCell = row.find('td.averageCell'); // find a <TD class="averageCell">.
var avgValue = parseFloat( avgCell.val());
In general, relying on positions to find things is brittle & fairly difficult to maintain; it's better to use IDs (where there is only one) or CSS classes (where there may be multiple.) Both of these are efficient, as well.
Hope this helps!

Categories

Resources