innerHTML not working inside event handler function (Javascript) - javascript

I have created a function, updatePrice, which I have tied to the "click" event on the checkbox and radio buttons in my HTML form. Each checkbox and radio basically represents an item, with it's price as the value property of these <input> elements. When I check or uncheck any box, the function fires, loops through all elements in the form, and updates the total price of all the checked items into a div element I have below my form, with the id tag "priceOutput".
The following code works perfectly, printing out: The price of this item is $(price of item).
function updatePrice() {
var price = 0
for (i=0;i<=form.length;i++) {
var element = form[i]
if(element.checked) {
price+=parseInt(element.value)
}
document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}
}
But, if I switch the the last line around, the line is not printed at all:
function updatePrice() {
var price = 0
for (i=0;i<=form.length;i++) {
var element = form[i]
if(element.checked) {
price+=parseInt(element.value)
}
}
document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}
Why must I write the line in the {} of the for in order to work. Doesn't the price variable's scope extend over the entire updatePrice function?
I'm still rather new to programming, so do forgive me if this is an elementary question.

It seems to me that it isn't printing because you are causing an error. Since array indexing starts at 0 your for loop should not use <= but rather < :
for (i=0;i<form.length;i++) {
...
}
The reason why nothing gets printed then is because on the last loop the function errors and you setting the inner HTML never gets executed.

Seems like there is an error with your code, how about adding var to your for loop and removing the = from i<=form.length
for (var i = 0; i < form.length; i++)

Related

Assigning random value from array to a button and using this value

I have a set of buttons set up with id, keys, values etc,
And an array with different values.
I want the user to be able to click on any button and this select at random from the array, this will when remove an image from the screen matching the value randomly picked from the array. It’s frustrating as I have been trying for ages! HELP!
function getrandom(){
var random = amounts[Math.floor(Math.random() * amounts.length)];
document.getElementById("task").innerHTML= "Your selected button revealed " + random;
for( var i = 0; i < amounts.length; i++){
if ( amounts[i] === random) {
arr.splice(i, 1);
}
}
}
Your code doesn't need a for-loop. Try this instead:
function getrandom() {
var randomIndex = Math.floor(Math.random() * amounts.length);
var random = amounts[randomIndex];
document.getElementById("task").innerHTML= "Your selected button revealed " + random;
amounts.splice(randomIndex, 1);
}
The root of your problem might have had something to do with the fact that you weren't "break;"ing out of the loop after you found the value, and so the loop kept going, checking all the other values. But because you had already removed an item from the array, it would potentially go out-of-bounds.
If this still doesn't work, you might be getting a null pointer error on the line:
document.getElementById("task").innerHTML= "Your selected button revealed " + random;
Check to make sure the "task" element actually exists in the HTML.

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;
}
}

Javascript, variables and if/else statements

I'm a complete Javascript newbie and I'm helping my friend with a small project for college.
The idea is that when a checkbox is checked an item is chosen, and then when a "total" button is pressed, the sum of the checked items is printed. I've been using if/else statements so if checked var staticprice = 29.00 and else var staticprice = 0.00, which appears to work fine until I total it. Adding the variable "staticprice" always returns a value of 0.00, even when checked.
It's very messy (as is my first attempt creating something like this): http://jsfiddle.net/mNmQs/180/
What am I missing here?
Cheers
Couple of things to make life easier, give your checkboxes a value, that is what it's there for! I've updated your fiddle to include the appropriate values per checkbox. The next is loops, simply loop your checkboxes, if checked, add the value of the checked input to the total:
var totalBtn = document.getElementById("total"),
checkboxes = document.getElementsByTagName("input");
totalBtn.onclick = function() {
var total = 0;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
total = total + parseInt(checkboxes[i].value);
}
}
alert(total);
}
http://jsfiddle.net/mNmQs/181/
You could change this line:
this.grandTotal= +seaprice + +stillprice + +staticprice;
To:
grandTotal= parseInt(seaprice,10) + parseInt(stillprice,10) + parseInt(staticprice,10);
In this case the problem is that you're trying to sum strings instead of numbers
JSFiddle example
HOWEVER it seems in this case there's no point in declaring your prices as strings. Of course unless you wanted to show the prices with in the format 0.00, otherwise just declare them as numbers and that should be better, like: var seaprice = 39.00; or var seaprice = 39.00; instead of var seaprice = "39.00";
Other fiddle

JavaScript validation, prevent duplicate input fields

I have a form with 10 Select Lists all have the same items. The items are populated from a PHP/MySQL array. The user needs to select one item per select list. I need to prevent the user from selecting the same item twice before submitting the form.
function checkDropdowns(){
var iDropdowns = 10;
var sValue;
var aValues = new Array();
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
sValue = document.getElementById('test' + i).value;
if ( !inArray(sValue, aValues) ){
aValues[iKey++] = sValue;
}else{
alert('Duplicate!');
return false;
}
}
return true;
}
Use javascript to add an event listener on the value change of the selects. That function would then loop through the selects taking the values into memory after having compared it to the values it had already. If the loop finds that the current select has an option that is already selected, put it back to default value and display a little message...
Or, still on a change event, take the value of the just selected item and remove all the items of this value in the 10 selects. So at the end the user will only have 1 choice, since he only sees the options he can choose. But be careful, if the user changes his mind on one select, make sure you add back the option you removed in the first place.
Option 2 is to be prefered as a user point of view, you will cause less frustration.
EDIT:
The code you are providing already does quite a lot... All you need now is something to revert the change if it is invalid:
var defaultValues = [];
function onLoadSelect(){//Please execute this on document load, or any event when the select are made available.
var iDropdowns = 10;
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
var sValue = document.getElementById('test' + i).value;
defaultValues['test' + i] = sValue;
}
}
Then, in your function's else, reset the value according to the defaults we have gathered:
else{
alert('Duplicate!');
document.getElementById('test' + i).value = defaultValues['test' + i];
return false;
}
I have written code, i think it can be improved but it works as you asked.
Put it in inside script tag under body so it loads after document.
Put id names of select/dropdown elements in id array.
Take a look: //took me 3 hours O_O
http://jsfiddle.net/techsin/TK9aX/15/
i think i need better strategy to approach programming.

Categories

Resources