Use the same function on multiple gridviews/tables - javascript

I have 6 asp gridviews that need the same calculations done on each of them. I could hard code the function 6 times over but looking for a more efficient way of doing it.
What I'm doing: There are 3 input boxes on each row, of each gv and I need to calculate the average and send it to a lbl in the last column.
Here is what I've done for the first gv:
function calculate() {
//********************
//Development Grid
//********************
//Find the number of rows in the grid
var rowCount = $('#devGV tr').length;
//Iterate through each row looking for the input boxes
for (var i = 0; i < rowCount; i++) {
//convert the total variable to an int
var total = 0;
parseInt(total);
//This variable is for tracking the number of actual fields that are populated.
//Not all the text fields will always be needed, so the average will not always be calculated by dividing by 3
var averNum = 0;
//Iterate through each text box
$("#devGV tr:eq(" + i + ")").find(":input[type=text]").each(function () {
//Convert the value to an int
var thisValue = parseInt($(this).val());
//In the value is blank, change it to 0 for calculation purposes
if (isNaN(thisValue) || thisValue == 0) {
thisValue = 0;
}
else {
averNum += 1;
}
total = (total + thisValue);
});
//Populate the totals label for each row
total = total / averNum;
total = total.toFixed(2);
//In the value is blank, change it to 0 for calculation purposes
if (isNaN(total)) {
total = 0;
}
$("#devGV tr:eq(" + i + ")").find("[class$='RowTotals']").text(total);
}
}
The above function is being trigger by 'onBlur' on each of the text fields. Is there a way I can make this block work for all the gridviews? I'm sure its just a matter of updating the selectors but I'm at a loss on how to do that.

Simplest is probably to pass a jquery object to calculate function:
function calculate(gv) {
Then use .find() in place of where you have the ID, for instance like this for the "find the number of rows in the grid":
var rowCount = gv.find('tr').length;
The reason I say it's easier to pass a jQuery object into the function (rather than the string ID of it, say) is that it lets you do something like this:
$('.some-gridview-css-class').each(function() {
calculate($(this));
});
Obviously replace that selector with whatever selector will identify your 6 gridviews for you.
EDIT: Oh I didn't read carefully enough. You want to do it onblur of a textbox. That means you want something like this:
$(document).ready(function() {
$(body).on('blur', 'input-fields-selector', function() {
calculate($(this).closest('gridview-selector'));
});
});
You have to replace input-fields-selector and gridview-selector with selectors to find the appropriate fields (which will depend on your HTML).

Related

count number of inputs which have value

js noob here - I'm trying to count the number of inputs that have a value out of a calculated number of them. The code I came up with trying to achieve that is the following:
var fields = document.querySelectorAll('[id^=example-]'), count = 0;
for (var z = 0; z <= fields.length; z++) {
if (fields[z].value != "") {
count = count + 1;
}
console.log('count is: ' + count);
}
Context: there are 3 inputs total and the above code executes on a click event.
Now the first time, this obviously runs fine if for example I set the value of the first input out of the three and returns [1]. The second time I update the same field's value, the counter increases again (logically).
Now, what I would like to achieve is to check all three inputs at the time the event fires & count how many of them have a value (and not increase the counter furthermore if they are already counted as having a value in the previous fire event).
Any help would be greatly appreciated. Thanks!
Shorter
const count = [...document.querySelectorAll('[id^=example-]')]
.filter(fld => fld.value.trim() !== "")
.length

calculating sum of values after combining results of multiple AJAX calls.

I am trying to write a JS function which calculates the sum of all visible rows in a column in a table.
The way the values in the column is filled is by making multiple ajax calls (50 rows at a time).
I am trying to keep track of no of requests sent and when I receive all responses back calculate the sum.
function onClickofCalculateButton() {
var noOfRequestsSent = 0;
var sum = 0;
var sucCallback = function(response) {
updateColumn(response, noOfRequestsSent, sum);
};
//Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}
in my updateColumn function()
function updateColumn(response, noOfRequestsSent, sum) {
noOfRequestsSent--;
//Do some logic to retrieve value of each row and add it to sum
if(noOfRequestsSent == 0) {
alert(sum);
}
}
However what is happening is the value of noOfRequestsSent is always equal to the actual number of requestssent even after subtracting it in updateColumn function. So it never reaches the condition where noOfRequestsSent == 0 and neither does the sum get added onto the previous value.
I guess I have to pass some object reference or something like pointers in C but I am unable to figure out how to do in JS.
You could try like this. Since you want to send variable as reference. In this way you can avoid global variables.
function onClickofCalculateButton() {
var noOfRequests = {
sent:0
};
var sum = 0;
var sucCallback = function(response) {
updateColumn(response, noOfRequests, sum);
};
//Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}
function updateColumn(response, noOfRequestsSent, sum) {
noOfRequests.sent--;
//Do some logic to retrieve value of each row and add it to sum
if(noOfRequests.sent == 0) {
alert(sum);
}
}

Noob Javascript auto total

Apologies for what I'm sure is a rather simple javascript question, but how would I get the following total funtion to calculate the total every time a cost is entered into the table, i.e. without having to press the total button to submit the form.
function totalIt() {
var qtys = document.getElementsByName("qty[]");
var total=0;
for (var i=1;i<=qtys.length;i++) {
calc(i);
var price = parseFloat(document.getElementById("price"+i).value);
total += isNaN(price)?0:price;
}
document.getElementById("total").value=isNaN(total)?"0.00":total.toFixed(2);
}
http://jsfiddle.net/mplungjan/jDfFU/
IF the qty fields are where the costs are being entered, then in your setup code, just hook totalIt up to the change (and possibly input, if you want immediate feedback) events:
var qtys = document.getElementsByName("qty[]");
var i;
for (i = 0; i < qtys.length; ++i) {
qtys[i].addEventListener("change", totalIt, false);
qtys[i].addEventListener("input", totalIt, false);
}
On modern browsers, if you hook input, you don't need to hook change; the above just allows for the possibility of older browsers by hooking change in case they don't support input.

How can I add javascript to a PDF document to count the number of checked boxes and enter the value into a textbox area?

So I have a PDF doc that has 25 check boxes called "cb1" through "cb25". I would like to be able to count the number of boxes that are checked and put that count into a text box area called "Points".
I'm not very familiar with either JS or PDF form creation but from what I've been able to dig up I think I'm close to getting it to work.
I have added the following code to the document level:
function CountCheckBoxes(aFieldsNames) {
// count field names that have been selected
var count = 0;
// loop through array of field names
for (i = 0; i < aFieldNames.length; i++) {
// for field names with a value of not Off increment counter
if (this.getField(aFieldNames[i]).value != "Off") count++;
} // end loop of field names
// return count
return count;
} // end CountCheckBoxes
I've tried adding the following code text box properties to execute JS on mouse up and as a calculated value, neither of which seem to work to populate the text box with a count of checked boxes.
// var define field names to be tested
var aFields = new Array('cb1', 'cb2', 'cb3', 'cb4', 'cb5', 'cb6', 'cb7', 'cb8', 'cb9', 'cb10', 'cb11', 'cb12', 'cb13', 'cb14', 'cb14', 'cb15', 'cb16', 'cb17', 'cb18', 'cb19', 'cb20', 'cb21', 'cb22', 'cb23', 'cb24', 'cb25');
// count field names that have been selected
event.value = CountCheckBoxes(aFields);
The code below should be added to the text field that keeps count of the boxes. To do so, right click on the form field then Properties -> Calculate -> Custom Calculation Script -> "Edit...".
var sum = 0;
for ( i = 1; i < 26; i++ ) {
f = "cb" + i;
field = getField(f);
if (field.isBoxChecked(0)) {
sum = sum + 1;
}
}
event.value = sum;
This is tested and working in an actual document. Here are some details about the code:
There is a loop that goes over all 25 fields, and creates a string for each one of their names. The string values are "cb1", "cb2" etc. Then gets the field by name. The isBoxChecked(0) field method, will return true if the box is checked. If a box is checked, the code will bump up the sum of all checked fields. When it's all done, the sum is assigned to the current text field.
Here is a link to the JS for Acrobat reference. It's quite useful when putting together samples like the one above.

JavaScript using isNaN to validate returns NaN

I have some code here that will make validations of whether or not the input from a text box is NOT an empty string and isNaN. When i do these validations on amounts entered, i would like it to add them up.. however when a user does not enter anything in one or more amount fields the program should just add entered fields. But instead i get NaN showing in the total field.
link to full code: http://jsfiddle.net/KxNqQ/
var $ = function (id) {
return document.getElementById(id);
}
var calculateBills = function () {
var myErrorFlag = "N";
for (i = 1; i <= 4; i++) {
AmountNumber = 'amount' + i;
AmountValue = $(AmountNumber).value;
if (AmountValue != "" && isNaN(AmountValue)) {
$(AmountNumber).style.color = "red";
myErrorFlag = "Y";
} else {
$(AmountNumber).style.color = "black";
myErrorFlag = "N";
}
}
if (myErrorFlag != "Y") {
var Amount = 0;
for (i = 1; i <= 4; i++) {
Amount += parseInt($('amount' + i).value,10);
}
$('total').value = Amount;
}
}
var clearFields = function () {
for (i = 1; i <= 4; i++) {
itemName = 'item' + i;
$(itemName).value = "";
}
for (i = 1; i <= 4; i++) {
amountName = 'amount' + i;
$(amountName).value = "";
}
$('total').value = "";
}
window.onload = function () {
$("clearfields").onclick = clearFields;
$("addbills").onclick = calculateBills;
}
I think you've got your requirements a little bit confused, or at the very least I was confused by them. So in order to answer your question, I'm going to rephrase the requirements so I understand them better. This is a useful exercise that I try to do when I'm not 100% sure of the requirements; if I can't get the requirements right, what's to say I'll get the code right?
So the requirements – as I understand them – are:
Given each amount input
When the input has a value
And that value is a number
Then add the value to the total
And make the input color black
But if the input does not have a value
Or that value is not a number
Then make the input color red
Going through your code, I can see a number of problems with it. First, I noticed that both AmountNumber and AmountValue are global variables, because they were not declared local with the var keyword. So before fixing our code, let's change that. Let's also change the variable names to something that more accurately describe what they are, hopefully making the code easier to understand:
var input = $('amount' + i);
var value = input.value;
Now, note that I chose to store the element in the input variable. This is so we don't have to look it up multiple times within the loop. Looking things up in the DOM can be expensive so we'll want to keep it to a minimum. There are other was to look up elements as well, such as getElementsByClassName, querySelector and querySelectorAll; those are left as an exercise for the reader to research and evaluate.
Next, in each iteration of the loop, you check that AmountValue is not a string and simultaneously is not a number:
if (AmountValue != "" && isNaN(AmountValue)) {
This will be true so long as AmountValue is truthy (which is the case for non-empty strings) and so long as isNaN thinks it's a number (which is the case for strings that contain numbers.) It really is rather confusing; if I understand your code correctly this clause is there to check for invalid input and if it is true should mark the input field red and set a flag. I.e. this is the but clause in the aforementioned requirements.
Let's rewrite this to be the when clause instead, we'll take care of the but later. Before we do that, let's look at the myErrorFlag. It's used – I think – to see whether all input is well formed and in that case, add it all up. Well, validation and summation can be done in one fell swoop, so let's get rid of the flag and sum the values while validating them. So we replace myErrorFlag with a total variable:
var total = 0;
Now, let's get back to our clause. The requirements say:
When the input has a value
And that value is a number
Then add the value to the total
In code, that should look something like this:
if (value && !isNaN(value)) {
total += parseInt(value, 10);
input.style.color = 'black';
}
There are a couple of things going on here. For one, the if statement has been turned on its head a bit from what it was. It first checks to see that value is truthy, then that it is a number. The second check can be a bit tricky to read, because it is essentially a double negation; in english it reads "is not not a number", i.e. "is a number". I'll leave it as an exercise for the reader to figure out whether there's a more easily understood way of writing this check.
Now what about the but clause in our requirements?
But if the input does not have a value
Or that value is not a number
Then make the input color red
Well, it's essentially the inverse of our previous statement, so let's simply add an else clause:
else {
input.style.color = 'red';
}
Because the requirements doesn't mention the total variable in this clause, it is simply ignored and doesn't show up in the end result.
Adding it all up (no pun intended) the code – with comments – looks like this:
var calculateBills = function () {
var total = 0;
for (i = 1; i <= 4; i++) {
// Given each amount input
var input = $('amount' + i);
var value = input.value;
if (value && !isNaN(value)) {
// When the input has a value
// And that value is a number
// Then add the value to the total
total += parseInt(value, 10);
// And make the input color black
input.style.color = 'black';
} else {
// But if the input does not have a value
// Or that value is not a number
// Then make the input color red
input.style.color = 'red';
}
}
$('total').value = total;
};
There are more things that could be learned from this to make for better code. For instance, this code will break if the number of inputs change, or if their id names change. This is because they are selected specifically by their IDs and as such, if those change then this code will no longer function.
Another potential issue is that we're setting inline styles on the inputs as we loop over them. This means that in order to keep this code up to date with the styling of the site, it'll have to change. Generally, mixing styling and functionality like this is not a good idea and should be avoided. One way of doing so is to use class names instead, and toggle these on and off. Incidentally, this could also help the previous problem I mentioned.
There are other problems as well, but we'll leave those for another day. Hope this helps!
Try this
var calculateBills = function () {
var Amount = 0;
for (i = 1; i <= 4; i++) {
var AmountElement = $('amount' + i),
AmountValue = AmountElement.value;
if (AmountValue != "" && !isNaN(AmountValue)) {
AmountElement.style.color = "red";
Amount += parseInt(AmountValue,10);
} else {
AmountElement.style.color = "";
}
}
$('total').value = Amount;
};
Demo
Anyway, instead of using elements with id like id="amount1", id="amount2", id="amount3", etc., you could use classes (e.g class="amount") and get them with .getElementsByClassName

Categories

Resources