How can I count only checked checkboxes in a PDF form? - javascript

There are a few check boxes in an Adobe PDF I have open in Acrobat. I want to count the checkboxes that have been checked and output the number in another textbox. How can I do that with JavaScript? Or other methods?

One possibility would be to set up a counter, enumerate all fields, check whether the field is a checkbox, and then whether its value is not "Off"; in that case increment the counter. A function doing that would look like this:
function countCheckedBoxes() {
var cntr = 0;
for (var i = 0; i < this.numFields; i++) {
var mf = this.getField(this.getNthFieldName(i));
if (mf.type == "checkbox") {
if (mf.value != "Off") {
cntr++;
}
}
}
if (cntr > 0) {
app.alert("The form has " + cntr + " checked boxes")
} else {
app.alert("The form has no checked boxes")
}
}
and that should do it.
As the number of checked boxes should go into another field, you would replace the evaluation of cntr with the following code:
if (cntr > 0) {
this.getField("boxCount").value = cntr + " boxes checked";
} else {
this.getField("boxCount").value = "no boxes checked";
}
...or simply enter the value of cntr.

I just was able to achieve this with a very simple script thanks to a script by George Johnson back in 2008.
What I did was create a text field, set it to read-only, and set it to be a custom computed value and put this in the script field:
// Initialize counter variable
var sum = 0;
// Loop through the fields
for (var i = 1; i < 180; i += 1) {
// Add one if check box is not Off
if (getField("CheckBox" + i).value !== "Off") {sum += 1;}
}
// Set this field's value to the sum
event.value = sum;
Important note: I have "CheckBox" + i and i < 180 in my for loop because all my checkboxes are named "CheckBox1", "CheckBox2", etc. through "Checkbox180".
If your checkboxes all have unique names, you'll need to put those names in an array and loop through it in your code. And if you only have, say, 15 checkboxes, then change the 180 in the script to 15.

Related

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.

Not All Check Boxes are Being Selected

When I check the boxes in the HTML file, it doesn't account for more than one being checked. How to I make it add the total of every box that is clicked, not just one?
for (i = 0; i < g_radSize.length; i++) {
if (g_chkExtras[i].checked === true) {
g_sExtras += g_chkExtras[i].value + ", ";
g_fTotal += gc_fExtrasPrice;
}
}
Full Code
// DO NOT DELETE ANYTHING IN THIS FILE
/*jsl:option explicit*/
/*jsl:declare $*//*jsl:declare addEventListener*//*jsl:declare isDigits*//*jsl:declare alert*//*jsl:declare blur*//*jsl:declare clearInterval*//*jsl:declare clearTimeout*//*jsl:declare close*//*jsl:declare closed*//*jsl:declare confirm*//*jsl:declare console*//*jsl:declare Debug*//*jsl:declare defaultStatus*//*jsl:declare document*//*jsl:declare event*//*jsl:declare focus*//*jsl:declare frames*//*jsl:declare getComputedStyle*//*jsl:declare history*//*jsl:declare Image*//*jsl:declare length*//*jsl:declare location*//*jsl:declare moveBy*//*jsl:declare moveTo*//*jsl:declare navigator*//*jsl:declare open*//*jsl:declare opener*//*jsl:declare opera*//*jsl:declare Option*//*jsl:declare parent*//*jsl:declare Number*//*jsl:declare parseInt*//*jsl:declare print*//*jsl:declare prompt*//*jsl:declare resizeBy*//*jsl:declare resizeTo*//*jsl:declare screen*//*jsl:declare scroll*//*jsl:declare scrollBy*//*jsl:declare scrollTo*//*jsl:declare setInterval*//*jsl:declare setTimeout*//*jsl:declare status*//*jsl:declare top*//*jsl:declare window*//*jsl:declare XMLHttpRequest*/
// Constants (Constants are variables that never change throughout the running of your program. They are almost always declared globally.)
var gc_fSandwichPrice = 5.99; // Price for each sandwich (Version 1 and 2 only)
var gc_fExtrasPrice = 1.50; // Price for each extra item
// GLOBAL VARS
// Global object vars
var g_divErrors;
var g_radSandwich;
var g_radSize;
var g_chkExtras;
// Other global vars
var g_fTotal;
var g_sSandwich;
var g_sSize;
var g_sExtras;
// DO IT: Hook up an event handler for window.onload to the Init function.
window.onload = Init;
function Init() {
// DO IT: Change the version number in the line below, if necessary, so it accurately reflects this particular version of Dirty Deli.
document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0";
// DO IT: grab and assign any html objects you need to work with
g_divErrors = document.getElementById("divErrors");
g_radSandwich = document.getElementsByName("radSandwich");
g_radSize = document.getElementsByName("radSize");
g_chkExtras = document.getElementsByName("chkExtras");
// DO IT: Set the innerHTML of spanExtrasPrice to gc_fExtrasPrice. Tip: Use the .toFixed() method to display it with 2 decimal places
document.getElementById("spanExtrasPrice").innerHTML = gc_fExtrasPrice.toFixed(2);
// DO IT: Hook up any event handlers you need
document.getElementById("btnCalculateTotal").onclick = CalculateTotal;
document.getElementById("btnProcessOrder").onclick = ProcessOrder;
// Version 2
// DO IT: You need to hook up an event handler that runs whenever the user selects a different Payment option.
//This is the "onchange" event. I suggest you use an anonymous function, and make use of the *selectedIndex* property to see if they chose the credit card.
//This function will check to see if the user selected the Credit card option. If they did, set the CSS visibility property to "visible", otherwise set it to "hidden".
document.getElementById("selPayment").onchange =
function() {
var divCreditCardInfo = document.getElementById ("divCreditCardInfo");
if (document.getElementById("selPayment").selectedIndex === 2) {
divCreditCardInfo.style.visibility = "visible";
}
else {
divCreditCardInfo.style.visibility = "hidden";
}
};
} // function Init()
// function Init
function CalculateTotal() {
// this function should be called when the user clicks the Calculate Total button. Its purpose is mainly to, well, calculate the total. Remember to hook up an appropriate event handler so this function will be called when they click.
// DO IT: clear out divErrors (set the innerHTML to an empty string)
g_divErrors.innerHTML = "";
// DO IT: Tip: you're going to be adding to g_fTotal. Remember: adding anything to garbage will always give you garbage. So how do you prevent this error?
// Same deal for g_sExtras.
g_fTotal = 0;
g_sExtras = " ";
/* DO IT:
Sandwich code - Version 1
Using an IF statement, see which radio button they checked, and assign the value of the selected sandwich to a global var name g_sSandwich.
If nothing is selected, set divErrors to "Select a sandwich", and exit the function.
Sandwich code - Version 2
Within each IF statement remove the line of code you wrote for Version 1.
Replace it with a call to a function (that you will write) named GetSandwichName().
When you call this function, pass it one parameter - the index of the radSandwich radio button that the user checked.
More info on the function itself is given below.
*/
/* if (g_radSandwich[0].checked === true) {
GetSandwichName(0);
}
else if (g_radSandwich[1].checked === true) {
GetSandwichName(1);
}
else if (g_radSandwich[2].checked === true) {
GetSandwichName(2);
}
else if (g_radSandwich[3].checked === true) {
GetSandwichName(3);
}
else {
g_divErrors.innerHTML = "Select a sandwich";
return;
}
*/
// Version 3
/* CONVERT: Sandwich code
Using a FOR loop and a single IF statement within the loop, see which radio button they checked.
When you find it, set g_sSandwich to the sandwich name
and break out of the loop using the break command.
If nothing is selected, set divErrors to "Select a sandwich", and exit the function.
But how do you know if nothing was selected? Use a boolean variable in the If statement,
then check its value after you get out of the loop.
Remember: Your code should be flexible enough so that if the number
of sandwiches change, your code can still work.
Afterall, that's one of the reasons we're using a loop.
Do NOT call the GetSandwichName() function. Incorporate its code here, and remove it.
*/
var iChecked = false;
var i;
for (i = 0; i < g_radSandwich.length; i++) {
if (g_radSandwich[i].checked) {
iChecked = true;
g_sSandwich = g_radSandwich[i].value;
break;
}
}
if (iChecked === false) {
g_divErrors.innerHTML = "Select a sandwich";
return;
}
// Version 1
/* DO IT:
This is the Size code.
Make sure they selected a size.
Update the total by adding the price of a sandwich (which is already declared as a constant) to the total
If nothing is selected, set divErrors to "Please choose a size", and exit the function.
Tip: An If Statement is the key here.
*/
// Version 2
/*
In this version, the sandwiches are not all the same price.
The price of each sandwich is contained within the title attribute of the radSandwich radio button for that sandwich
(take a look at the html to verify this).
So, modify the IF statement from Version 1. You need to call a function (that you will write) named GetSizeUpdateTotal(). More on that below.
*/
/*
if (g_radSize[0].checked === true) {
GetSizeUpdateTotal(0);
}
else if (g_radSize[1].checked === true) {
GetSizeUpdateTotal(1);
}
else if (g_radSize[2].checked === true) {
GetSizeUpdateTotal(2);
}
else {
g_divErrors.innerHTML = "Please choose a size";
return;
}
*/
// Version 3
/* CONVERT: Size code
Once again, using a FOR loop and a single IF statement within the loop,
see which radio button they checked, get the price and update the total just like you did previously.
Then break out of the loop using the break command.
If nothing is selected, set divErrors to "Please choose a size", and exit the function.
Do NOT call the GetSizeUpdateTotal() function. Incorporate its code here, and remove it.
*/
iChecked = false;
var price;
for (i = 0; i < g_radSize.length; i++) {
if (g_radSize[i].checked) {
iChecked = true;
price = g_radSize[i].title;
price = price.substr(1);
price += Number(price);
g_sSize = g_radSize[i].value;
g_fTotal += price;
break;
}
}
if (iChecked === false) {
g_divErrors.innerHTML = "Please choose a size";
return;
}
/* DO IT:
"Extras" code - Version 1
Using an IF statement, see which extra(s) they checked. For each extra selected, do the following:
Concatenate the value of the selected extra to a global var name g_sExtras.
Update the Total with the price of the Extra.
"Extras" code - Version 2
Remove each IF statement you wrote for Version 1. Replace it with a call to a function (that you will write) named GetExtraUpdateTotal().
When you call this function, pass it one parameter - the index of the chkExtras checkbox that the user checked.
More info on the function itself is given below.
*/
/*
GetExtraUpdateTotal(0);
GetExtraUpdateTotal(1);
GetExtraUpdateTotal(2); */
// Version 3
/* CONVERT: "Extras" code
Again, using a FOR loop and a single IF statement within the loop, do what needs to be done.
Remember NOT to break out of the loop when you find a checked checkbox (there may be more).
Do NOT call the GetExtraUpdateTotal() function. Incorporate its code here, and remove it.
*/
for (i = 0; i < g_radSize.length; i++) {
if (g_chkExtras[i].checked === true) {
g_sExtras += g_chkExtras[i].value + ", ";
g_fTotal += gc_fExtrasPrice;
}
}
/* ****** That's it -- you're done with the loops. ******* */
// END Version 3
/* DO IT:
Optional fun: Remove the trailing comma on the last extra.
HINT: use the length property and the substr() method.
*/
// Version 1
// DO IT: Assign the total to the txtTotal textbox. Include a dollar sign and use .toFixed() to display 2 decimal places
document.getElementById("txtTotal").value = "$" + parseFloat(g_fTotal).toFixed(2); //Got help from stack overflow with the parseFloat than researched on w3schools on how to use it.
} // function CalculateTotal
// Version 2
/* DO IT:
Declare function GetSandwichName().
This function takes one parameter, named p_iSandwichIndex,
which is a radSandwich radio button index, i.e. the index of the Sandwich they selected.
It assigns the value of the selected sandwich to a global var name g_sSandwich.
*/
// END Version 2
// Version 2
/* DO IT:
Declare function GetSizeUpdateTotal().
This function takes one parameter, named p_iSizeIndex, which is a radSize radio button index,
i.e. the index of the radSize radio button that they selected.
The function should assign the *value* of the selected size to a global var name g_sSize.
Also, it must update the Total with the price for the size they selected.
The price is located in the title attribute of the radio button (take a look).
Remember that (using dot notation) you can access any object attribute you want, once you grab the object.
But the price in the title attribute contains a dollar sign,
and you want everything AFTER the dollar sign.
Use the substr() method to get the entire string, starting with the SECOND character in the string.
Look back on our class notes to see how we did this.
Use an alert to see that you got what you intended.
Then, convert that string to a number and add it to the Total.
TIP: Declare local vars as necessary.
*/
// Version 2
/* DO IT:
Declare function GetExtraUpdateTotal().
This function takes one parameter, named p_iExtraIndex, which is a chkExtras checkbox index, i.e. the index of an extra they selected.
Use an if statement to see if this particular checkbox is checked. If it is, then do the following:
Concatenate the value of the selected extra to a global var name g_sExtras.
Update the Total with the price of the Extra.
*/
function ProcessOrder() {
// This function should run when the ProcessOrder button is clicked.
// Version 2
// DO IT: declare any local vars you may need
var txtName = document.getElementById("txtName");
var txtMonth = document.getElementById("txtMonth");
var selPayment = document.getElementById("selPayment");
var selYear = document.getElementById("selYear");
var txtCreditCardNbr = document.getElementById("txtCreditCardNbr");
var month;
// Version 2
// DO IT: Before you do your error checking, does anything need to be initialized to an empty string? Now's the time to do it.
document.getElementById("divOrder").innerHTML = "";
g_divErrors.innerHTML = "";
// Version 2
// DO IT: If the name field is blank, display "Enter customer's name", set the focus and get out.
if (txtName.value === "") {
g_divErrors.innerHTML = "Enter customer's name";
txtName.focus();
return;
}
// Version 2
/* DO IT: Credit Card Code
Use an IF statement to determine if the user selected the credit card option in the selPayment dropdown
If they did, you need to do the following:
if the credit card number field was left blank or the contents of the field is not a number, display (in divErrors) the message shown in the working version, put focus on the card number field and get out.
if the month field was left blank or the contents of the field is not a number, display the message shown in the working version, put focus on the month field and get out.
if the month they entered is less than 1 or > 12, display the message shown in the working version, put focus on the month field and get out.
TIP: Remember to convert the txtMonth value to a number before you do your comparison.
if they neglected to select a year, display the message shown in the working version, put focus on the year field and get out.
*/
// END Version 2
// The following section I got assistance from another classmate.
if (selPayment.selectedIndex === 2) {
if ((txtCreditCardNbr.value === "") || (isDigits(txtCreditCardNbr.value) === false)) {
g_divErrors.innerHTML = "Enter your card number using only digits";
txtCreditCardNbr.focus();
return;
} else if ((txtMonth.value === "") || (isDigits(txtMonth.value) === false)) {
g_divErrors.innerHTML = "Enter month using only digits";
txtMonth.focus();
return;
} else {
month = Number(txtMonth.value);
if ((month < 1) || (month > 12)) {
g_divErrors.innerHTML = "Enter month between 1 and 12";
txtMonth.focus();
return;
}
}
if (selYear.selectedIndex === 0) {
g_divErrors.innerHTML = "Please select a year";
selYear.focus();
return;
}
}
// DO IT: Concatenate the appropriate msg into divOrder. The Welcome msg is within an h3 tag. Every other line is within a p tag. The last line is in bold.
/* Version 1:
Do not include the user's name in the welcome message.
Do not include the "Paid by" statement.
*/
/* Version 2:
Include the user's name in the welcome message.
Include the "Paid by" statement.
*/
document.getElementById("divOrder").innerHTML =
"<h3>Welcome to Dirty Deli!</h3>" + txtName.value + "<br>" +
"You have ordered a " + g_sSize + " " + g_sSandwich + " with " + g_sExtras + "<br>" +
"Your total is " + document.getElementById("txtTotal").value + "<br>" +
"Paid with " + selPayment.value + "<br>" + "<br>" +
"<strong>Have a nice day!</strong>";
} // function ProcessOrder
g_radSize is an array of (one or two )array. hence the loop is running for amount of elements g_radSize contain.
Normally, you should be using g_chkExtras.length instead of g_radSize.length.
for (i = 0; i < g_chkExtras.length; i++) {
if (g_chkExtras[i].checked === true) {
g_sExtras += g_chkExtras[i].value + ", ";
g_fTotal += gc_fExtrasPrice;
}
}

Use the same function on multiple gridviews/tables

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).

Jquery automatically select next X checkboxes

I'm working on a website for a theater where a customer can reserve tickets.
Choosing a chair works as follows:
You select how many chairs you want in the dropdown menu (we will call this X).
You tick the checkboxes where you want to sit (maximum of X).
Upon having chosen all X checkboxes, the other checkboxes turn grey (unclickable).
There are ofcourse also chairs that have already been reserved. These simply don't have a checkbox. The value of the checkbox is the same as the chair's unique ID.
This works fine except I want the system to automatically tick the next checkboxes (next 3 if the customer has chosen 4).
I have updated my code to this:
var _X = $('#PlaatsenDropdown').val() - 1;
var _id = $(this).id;
var _counter = _id + _X;
for(var i = _id; i <= _counter; i++) {
if($(this).nextAll().is('disabled')) {
alert('No seats available');
} else {
alert('Chairs available');
}
}
The id is also the chair number, so I just take that and do some calculations with it to use in the for loop.
This however, doesn't show me anything. I think there might be something wrong with the calculations but I can't figure out what :S.
You can create an array of ID strings similar to what you've done already. Then loop through the array with the 'disabled' test.
Pseudo code:
val = selected_chair_ID
for (i=0; i < desired_number_chairs; i++) {
search_right.push('#' + val + i);
search_left.push(('#' + val - i);
}
found = true;
for (j = 0; j < search_right.length; j++) { // Check chairs to the right
$(search_right[j]).....// Disabled check
if (disabled...) {
found=false;
}
if (!found) {
check chairs to the left
}
if (!found) // out of luck

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