JavaScript - Very Simple Problem With Using Variables Between Functions In A .js (grrrrr)
Hi I am using a .js with 3 functions in it
1st function getPeriod is to extract the index of a selected list item 2nd function getRadios is to get the value from a selected radio button 3rd function calculateAmount uses if statments and follows a course depending on which index was selected from the list item in the 1st functino ie . 0,1,or 2 The problem is that the index value is unidentified in the 3rd function when i try to use it in the if statement, but the value of the radio button, the variable "cigs" works... I want to know how to allow the index value to work in the 3rd function I know this is a very silly problem but I cant spend any more time trying to figure it out ...code below ...Thanks ! [code] var index = 0; var element = ""; var cigs = 0; // get the selected item in the list with id listId function getPeriod(listId){ // find the index of the selected item index = document.getElementById(listId).selectedIndex; // use the index to access the text of the selected item element = document.getElementById(listId).options[index].text; // put the favorite into the text field document.getElementById('period').value=index; return index; } function getRadios(what){ // get the cigs value j=what.cigs.length; //alert(j) for (i=0; i<j; i++){ if(what.cigs[i].checked) cigs = what.cigs[i].value } what.buttons.value = (cigs) return cigs; } function calculateAmount (){ if (index = 0) { total = (8.5 * cigs * 182); } else if ( index = 1 ) { total = (8.5 * cigs * 365); } else if (index = 2) { total = (8.5 * cigs * 730); } document.getElementById('total').value=total; } [code] Similar TutorialsHi, Need some help here. To formulate the problem simple i have two buttons with the onclick function: Code: <a href="#" ONCLICK="function1('this')">Click for this!</a> <a href="#" ONCLICK="function1('that')">Click for that!</a> When I click this button I actually need to pass the value 'this' or 'that' to function2.. Code: <script language="javascript"> var name = '' function1(name) { ??? } function2() { document.all.textbox.value = name; } </script> I guess what im asking is how can you set a variable by one onclick function and then use it in any other function? Thanks a bunch! Col I've noticed that if you declare a variable in one function, then call another function, the variables cannot be accessed in that function. Is there any way to get the value of a variable declared in a different function?
Hi I want help with trying to pass some variables from one function to another. so with the following example: Code: // main body of script function exercise() { fnLLR_Calculate(); fnLLR_Calculate2(); } function fnLLR_Calculate() { //-------Gets values from web page------// var $Shares; _set($Shares, _getText(_textbox("CALC_STOCK_INPUT"))); $Shares = Number($Shares); _log("$Shares =" + $Shares); var $GrantPrice; _set($GrantPrice, _getText(_textbox("GRANT_PRICE_INPUT"))); $GrantPrice = Number($GrantPrice); _log("$GrantPrice = " + $GrantPrice); var $FMVPrice; _set($FMVPrice, _getText(_textbox("FAIR_MARKET_VALUE"))); $FMVPrice = parseFloat($FMVPrice).toFixed(2); _log("$FMVPrice = " + $FMVPrice); var $TaxWitholdRate; _set($TaxWitholdRate, _getText(_textbox("TAX_WITHHOLDING_RATE"))); $TaxWitholdRate = $TaxWitholdRate / 100; _log("$TaxWitholdRate = " + $TaxWitholdRate); } function fnLLR_Calculate2() { //----uses values from fucntion 1 to calculate----// $Result_Shares = ($Shares- $GrantPrice) * $TaxWitholdRate / $FMVPrice; $Result_Shares = $Result_Shares.toFixed(0); _log("$Result_Shares = " + $Result_Shares); } So i need to pass some variables from function fnLLR_Calculate to fnLLR_Calculate2. What is the best way to do this? Hi everyone, I am working on an assignment and require a little bit of assistance. I have a form (an order form) where I am required to validate the required entries - I have managed to do this with the textbox field no problems. Where I am coming unstuck is with the following items. homePhone - numbers only and max 10 numbers for validation postCode - same as above email validation of @ and . How do I validate comboboxs so that if nothing is selected an alert shows? If the "other address" radiobutton is checked how do I have the text boxes only validate on check? How do I validate the textarea when "do you want a card message" is ticked? I have been working on this for the past week and a bit and have done a fair amount of research and tried to implement various pieces of code I have found with no luck. I have removed some of the select objects to cut down on the amount of code. I am not expecting anyone to write my assignment for me, just wanting assistance to help me learn and become more proficient in JS Regards BP Code: <html> <head> <title>Online Order Form</title> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <meta name="author" content="Jeremy Porteous"> <script type="text/javascript"> <!-- function validate(){ var form=document.getElementById("orderForm"); var Name=form["fullName"].value; var fullName_err=document.getElementById("fullName_err"); var address=form["address"].value; var address_err=document.getElementById("address_err"); var location=form["location"].value; var location_err=document.getElementById("location_err"); var postcode=form["postcode"].value; var postcode_err=document.getElementById("postcode_err"); var homePhone=form["homePhone"].value; var homephone_err=document.getElementById("homePhone_err"); var email=form["email"].value; var email_err=document.getElementById("email_err"); var checkbox=form["card"].value; var street=form["street"].value; var street_err=document.getElementById("street_err"); var otherLocation=form["otherLocation"].value; var otherLocation_err=document.getElementById("otherLocation_err"); var otherPostcode=form["otherPostcode"].value; var otherPostcode_err=document.getElementById("otherPostcode_err"); if(Name==""){ fullName_err.innerHTML="Please enter your Full Name"; }else{ fullName_err.innerHTML=""; } if(address==""){ address_err.innerHTML="Please enter your Street Address"; }else{ address_err.innerHTML=""; } if(location==""){ location_err.innerHTML="Please enter your Surburb/Town"; }else{ location_err.innerHTML=""; } if(postcode==""){ postcode_err.innerHTML="Please enter your Postcode"; }else{ postcode_err.innerHTML=""; } if(homePhone==""){ homePhone_err.innerHTML="Please enter your Phone Number"; }else{ homePhone_err.innerHTML=""; } if(email==""){ email_err.innerHTML="Please enter a valid Email"; }else{ email_err.innerHTML=""; } if(street==""){ street_err.innerHTML="Please enter Street Address"; }else{ street_err.innerHTML=""; } if(otherLocation==""){ otherLocation_err.innerHTML="Please enter Suburb/Town"; }else{ otherLocation_err.innterHTML=""; } if(otherPostcode==""){ otherPostcode_err.innerHTML="Please enter Postcode"; }else{ otherPostcode_err.innerHTML=""; } if(Name=="" || address=="" || location=="" || postcode=="" || homePhone=="" || email=="" || street=="" || otherLocation=="" || otherPostcode=="") { alert("Please Check form and fill in form data correctly"); return false; }else{ return true; } } --> </script> <h2>Joes Online Order Form</h2> <h5>* denotes a required field</h5> <h3><u>Your Details</u></h3> <form id="orderForm" name="orderForm" method="post" action="" onsubmit="javascript:return validate()"> <!-- The form user is required to fill in some personal information * is a required field --> <!-- Input fields will be validated --> <h4>*Name: <label><input type="text" id="fullName" size="35"></label> <label id="fullName_err" style="color:#FF0000; font-style:italic;"></label></h4> <h4>* Address: <label><input type="text" id="address" size="30"></label> <label id="address_err" style="color:#FF0000; font-style:italic;"></label> * Suburb/Town: <label><input type="text" id="location" size="30"></label> <label id="location_err" style="color:#FF0000; font-style:italic;"></label></h4> <!-- The input field for "state" is a dropdown combo box --> <h4>* State: <select name="homeState" size="0"> <option value="State">Select your State</option> <option value="ACT">ACT</option> <option value="NSW">NSW</option> </select> <label id="homeState_err" style="color:#FF0000; font-style:italic;"></label> * Postcode: <label><input type="text" id="postcode" maxlength="4" size="4"></label> <label id="postcode_err" style="color:#FF0000; font-style:italic;"></label></h4> <h4>* Home Phone: <label><input type="text" id="homePhone" maxlength="10" size="10"></label> <label id="homePhone_err" style="color:#FF0000; font-style:italic;"></label></h4> <h5>Work Phone: <input type="text" id="workPhone" maxlength="10" size="10"> Fax: <input type="text" id="Fax" maxlength="10" size="10"></h5> <h4>* Email: <label><input type="text" id="email" size="30"></label> <label id="email_err" style="color:#FF0000; font-style:italic;"></label></h4> <!-- The input fields for "type" and "expDate" are dropdown combo boxes --> <h4><em>Credit Card Details</em></h4> <h4>* Type: <select name="creditCard" size="0"> <option value="creditCard">Select your Credit Card</option> <option value="visa">Visa</option> <option value="mastercard">Master Card</option> </select> * Exp Date: <select name="expMonth" size="0"> <option value="Jan">Jan</option> <option value="Feb">Feb</option> <option value="Mar">Mar</option> </select> <select name="expYear" size="0"> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> </select></h4> <!-- Using the combo boxes the user can select type of basket and qty --> <h4><em>Purchase Details</em></h4> <h4>* Basket Type: <select name="basketType" size="0"> <option value="Select a Basket">Select a Basket</option> <option value="1A">1A</option> <option value="1B">1B</option> </select> * Qty: <select name="quantity" size="0"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select></h4> <h4><b>* Deliver To:</b></h4> <!-- Radio buttons are mutually exclusive --> <h4><input type="radio" id="homeDel" name="delAddress" value="homeAddress" checked> Home Address</h4> <h4><input type="radio" id="otherDel" name="delAddress" value="otherAddress"> Other Address</h4> <!-- the following is for the "Other Address option" --> <h3><u>Other Address Details</u></h3> <h4>* Street: <label><input type="text" id="street" size="30"></label> <label id="street_err" style="color:#FF0000; font-style:italic;"></label> <!-- The input field for "state" is a dropdown combo box --> * Suburb/Town: <label><input type="text" id="otherLocation" size="30" ></label> <label id="otherLocation_err" style="color:#FF0000; font-style:italic;"></label></h4> <h4>* State: <select name="state" size="0"> <option value="State">Select the State</option> <option value="ACT">ACT</option> <option value="NSW">NSW</option> </select> * Postcode: <input type="text" id="otherPostcode" maxlength="4" size="4"> <label id="otherPostcode_err" style="color:#FF0000; font-style:italic;"></label></h4> <h4><em><b>* Date Delivery Required</b></em> <select name="delDay" size="0"> <option value="01">01</option> <option value="02">02</option> <option value="03">03</option> <option value="04">04</option> </select> <select name="delMonth" size="0"> <option value="Jan">Jan</option> <option value="Feb">Feb</option> <option value="Mar">Mar</option> <option value="Apr">Apr</option> </select> <select name="delYear" size="0"> <option value="2012">2012</option> </select></h4> <h5>Would you like to include a card? <input type="checkbox" id="card"> <label id="card_err" style="color:#FF0000; font-style:italic;"></label></h5> <!-- Text box message will only be submitted if checkbox is ticked --> <p>Leave a personal message for the card<br> <textarea name="text" id="cardMessage" rows="5" cols="28"> Enter your message here</textarea></p> <p>***Click on <b>Submit</b> when complete or <b>Clear Form</b> to reset form***</p> <input type="submit" id="submit" value="Submit"> <input type="reset" value="Clear Form" onClick="reset"> </form> </body> </html> hi. i know a little php, but new to javascript. much of the syntax is identical. in reading the new rhino book (flanagan 6th), he gives the following example: Code: var square = function(x) { return x*x; }; okay, but then he does this: Code: square(plus1(y)) as an example of "invoking two functions in one expresson". (Prior he gives an example of defining a function with plus1, which is how I normally think of functions.) uh, square is a *variable*, but he is using it as a FUNCTION. Can somebody help me understand how this can be? how it works? I'm having trouble conceptualizng how we use a variable as a function. I recently started designing websites, I'm pretty good with working in the design area of expertise. However I am not so great at the development part. I have had little to no experience with java programming. I am putting e commerce on my clients site. He is selling an item that varies in price depending on what size it is. What I am trying to do is have a input for the length and the width and then display the price. I have configured the length and width to multiply and can display the total but I don't know what the if then statement would look like for the price. So lets say the user puts in 4 length and 4 width. I can display 16. But I want to take that and say if =16 then display $21.50 or whatever the cost would be. But I cannot figure out how to code it right for the if then part and then the display part. I am very new to java programming and think i might be a little out of my league with this project but any help you can offer would be great. thank you.
I want to call both of these functions with the same "onclick". Right now the two html onclicks that call each of these are below onclick="changeIt({IMAGE_VALUE_LOOP})" onclick="return toggleDiv('preview')" (where preview is the id of the div) Code: function changeIt() { var theImg = document.getElementsByTagName('img')[0].src; var x = theImg.split("/"); var t = x.length-1; var y = x[t]; } function toggleDiv(a){ var e=document.getElementById(a); if(!e)return true; if(e.style.display=="none"){ e.style.display="block" } else { e.style.display="$div" } return true; } Hello, Problem 1: I have a function and it sets a value to a certain number according to the input. However, I don't want the function to print out the value to the screen, but instead temporarily save it for me to use throughout the whole script. I am a newbie and please help me. For example, I make this code: function add1(x) { var x = x + 1 return x; } and I call the function: add1(0); document.write("value = " + x + "<BR>"); Whenever I do this, document.write doesn't print out value = 1, it doesn't even print anything except for the headers, etc. Is there anyway to set the var x to be a value valid throughout the whole script instead of just the function itself? I really need help on this, thanks. Problem 2: I want to get a code working. Basically, I use a ram to "ram the gate". I set the damage done each turn, and the Gate's Health too. So for example, my ram's damage is 10 and the gate's health is 200. It would take 20 times to totally breach the gates(i.e., for gate health to become 0). When I use the following code, the total damage is the same throughout the whole looping until the gatehealth reaches 0 which makes it boring, is there anyway to modify or improve the script such that when I loop, the MiscDamage would be different for all the turns? thanks! Once again I apologize for asking such a noob-ish and very strange.... question. Quote: <script language="JavaScript" type="text/javascript"> <!-- // Begin function RamGates(Ram, Attack, Gate) { //introducing variables to be used var BaseDamage = 0; var FullDamage = 0; var MiscDamage = 0; var TotalDamage = 0; var GateHealth = 0; switch (Ram) { //ignore this part just comparing ram types case "Explosive": BaseDamage="10"; break; case "Wooden": BaseDamage="20"; break; case "Steel": BaseDamage="30"; break; case "", "?": default: BaseDamage="Failed to recognize Ram"; } switch (Attack) { //ignore this just comparing attack values case 0: FullDamage = BaseDamage; break; case 1: FullDamage = (BaseDamage*2)-8; break; case 2: FullDamage = (BaseDamage*2)-6; break; case 3: FullDamage = (BaseDamage*2)-4; break; case 4: FullDamage = (BaseDamage*2)-2; break; case 5: FullDamage = BaseDamage*2; break; case "", "?": default: FullDamage="Failed to recognize Attack"; } switch (Ram) { //this part is what i need help on, i need the loop function to keep using this to generate different "lucky damages" each time to make it interesting, i.e., first ram = 11 second ram = 16 third ram = 14 and so on..... case "Explosive": MiscDamage = Math.floor(Math.random()*21+10); break; case "Wooden": MiscDamage = Math.floor(Math.random()*6+0); break; case "Steel": MiscDamage = Math.floor(Math.random()*11+5); break; case "", "?": default: MiscDamage="Failed to recognize Ram"; } switch (Gate) { //ignore this part just comparing gate types to generate gate health case "Wooden": GateHealth = 50; break; case "Brick": GateHealth = 75; break; case "Small Stone": GateHealth = 90; break; case "Large Stone": GateHealth = 120; break; case "Granite": GateHealth = 140; break; case "Iron": GateHealth = 175; break; case "R Iron": GateHealth = 190; break; case "Thick Iron": GateHealth = 210; break; case "Steel": GateHealth = 230; break; case "R Steel": GateHealth = 250; break; case "Thick Steel": GateHealth = 275; break; case "Steel Iron Mix": GateHealth = 280; break; case "Thick Steel Iron Mix": GateHealth = 300; break; case "Strong Ruby Steel Mix": GateHealth = 400; break; case "Strong Sapphire Steel Mix": GateHealth = 450; break; case "R Thick Large Diamond Steel Mix": GateHealth = 500; break; case "", "?": default: GateHealth = "Failed to recognize Gate"; } TotalDamage = FullDamage + MiscDamage; with (document) { write ("Soldiers, " + "RAM THE GATES!" + "<BR>"); } while (GateHealth >= 0) //loops until gate health is lower than 0 { //need help! how to make it such that the loop will rerun the switching of ram for generating random misc(lucky) damages document.write ("Lucky Damage done = " + MiscDamage + "<BR>"); document.write ("Total Damage done = " + TotalDamage + "<BR>"); var GateHealth = GateHealth - TotalDamage document.write("Current GateHealth = " + GateHealth + "<BR>"); } } RamGates("Explosive", 5, "R Thick Large Diamond Steel Mix"); //function calling // End --> </script> All -- I have a JavaScript config file called gameSetting.js which contains a bunch of variables which configures a particular game. I also have a shared JavaScript library which uses the variables in gameSetting.js, which I include like so: <script type="text/javascript" src="gameSetting.js" ></script> <script type="text/javascript" src="gameLibrary.js" ></script> In gameSetting.js I have: $(document).ready(function() { // call some functions / classes in gameLibrary.js } in Firefox, Safari, and Chrome, this works fine. However, in IE, when it's parsing gameSetting.js, it complains that the functions that live in gameLibrary.js aren't defined. When it gets to parsing gameLibrary.js, the variables in gameSetting.js are reported as not being defined. I've tried dynamically bootstrapping the gameLibrary file using this function in document.ready for dynamic load... $.getScript("gameLibrary.js"); However, the same problem still happens in IE, where when it parses the files individually it's not taking into context the file/variables that came before, so it's not an out of load order problem. My options a 1) collapsing all the functions in gameLibrary.js and variables in gameSetting.js into one file. However, this is not practical because this is dealing with literally hundreds of games, and having a gameLibrary.js in ONE location for ONE update is what makes most logical sense. 2) figure out a way to get this to work where variables in file1 are accessible to file2 in IE (as it seems they are in other browsers). jQuery seems to be able to have multiple plugins that all refer to the based jQuery-1.3.2.js, so I know there is a way to get this to work. Help appreciated. Nero Code: window.onload = makeMenus; var currentSlide = null; var timeID = null; var leftPos = 0; function makeMenus(){ var slideMenus = new Array(); var allElems = document.getElementsByTagName("*"); for (var i=0; i < allElems.length; i++){ if (allElems[i].classname == "slideMenu")slideMenus.push(allElems[i]); } for (var i = 0; i < slideMenus.length; i++){ slideMenus[i].onclick = showSlide; } document.getElementById("head").onclick = closeslide; document.getElementById("main").onclick = closeSlide; } function showSlide(){ var slideList = this.getElementsByTagName('ul')[0]; if ((currentSlide != null) == slideList { closeSlide; }else { closeSlide; currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval("moveSlide()", 1); } } function closeSlide(){ clearInterval(timeID); currentSlide.style.left = 0 + "px"; currentSlide.style.display = "none"; currentSlide = null; } function moveSlide(){ leftPos + 5; if (leftPos <= 220){ currentSlide.style.left = leftPos + "px"; }else { clearInterval(timeID); leftPos = 0; } } The HTML is a bit lengthy. Wasn't sure it was necessary here. Hello, I'm taking Computer Logic in college. I only am truly familiar with HTML and CSS and minimal web hosting stuff. I REALLY want to learn how to program, however. Anyway, we are doing classes/objects and functions. I am trying to figure out how to do this exercise. She starts with having us make this page that has a form that lets you select one of three radio buttons that will change the background color of the web page, along with that there is two text boxes to put a first name and last name. Then there is a button to click which puts your full name concatenated in another box below. All of this, is done, and I pretty much THINK I understand what is going on. Here is the code that we did to get this to happen: Code: <html> <head> <title>Computer Logic in class</title> <script type="text/javascript"> var nextColor = ""; var BR = "<br />"; function setColor(newColor) { nextColor = newColor; } function changeColor() { document.body.bgColor = nextColor; } function displayName() { var firstName = document.ColorAndText.firstName.value; var lastName = document.ColorAndText.lastName.value; document.ColorAndText.fullName.value = firstName + " " + lastName; } </script> </head> <body bgcolor="red"> <form name="ColorAndText" action = ""> <input type="radio" name="colors" value="Blue" onclick="setColor(this.value)"/> Blue <br /> <input type="radio" name="colors" value="LightYellow" onclick="setColor(this.value)"/> Light Yellow <br /> <input type="radio" name="colors" value="Yellow" onclick="setColor(this.value)"/> Yellow <br /> <input type="button" name="changeButton" value="changeColor" onclick="changeColor()" /> <br /> <input type="text" name="firstName" value="First Name" size="40" /><br /> <input type="text" name="lastName" value="Last Name" size="40" /><br /> <input type="text" name="fullName" readonly="true" size="40" /><br /> <input type="button" name="displayButton" value="Display name" onclick="displayName()" /> <br /> </form> </body> </html> Okay, now, I have and can do that. Seems to make sense. Now, then, the actual program I need to make is from the following exercises: Activity 3-4 The owner of a flower shop wants you to develop a form for use on the shop's web site. The form should have a single text box for the user to enter his or her name. Under the text box should be a group of radio buttons for three different kinds of flowers: Roses, Carnations, and Daisies. Below the radio buttons should be a button labeled Request Info, with a read-only text box under it for thanking the user for requesting information. This program doesn't need any functions or onclick attributes for the graphical elements. Okay, here is the code that does that, very simple HTML. Code: <html> <head> <title>Computer Logic in class</title> <script type="text/javascript"> var nextFlower = ""; var BR = "<br />"; function setFlower(newFlower) { nextFlower = newFlower; } function displayMessage() { var firstName = document.Flowers.nameBox.value; document.Flowers.fullName.value = firstName + "," + nextFlower; } </script> </head> <body bgcolor="white"> <form name="Flowers" action = ""> <input type="text" name="nameBox" value="Namebox" size="60"><br /> <input type="radio" name="flowers" value="Roses" onclick="setFlower(this.value)"/> Roses <br /> <input type="radio" name="flowers" value="Carnations" onclick="setFlower(this.value)"/> Carnations <br /> <input type="radio" name="flowers" value="Daisies" onclick="setFlower(this.value)"/> Daisies <br /> <input type="button" name="displayButton" value="Request Info" onclick="displayMessage(this.value)" /> <br /><br /> <input type="text" name="thankyou" readonly="true" size="100" value="Thanks for using this program" /> </form> </body> </html> Okay, now is where I'm stuck. The following exercise is as follows: The flower shop owner in the previous activity wants to see where you can make the form interactive and asks you to have the form display a message in the bottom text box that includes the user's name, a comma, and the words "thank you for your inquiry about" followed by the flower name the user selected. Write a function named displayMessage() that accesses the user's name from the first text box and displays the message in the read-only text box. You also need to make the Request Info button call the displayMessage() function when it's clicked. Using Javascript, make this form active by including event triggers and functions. My teacher has said that I should be able to do this by just referencing these two previous pages of code that I have already pasted. I feel like I am missing something, that I need to be doing something and it's just not working for me. I'm actually really really stuck on this. I haven't even gotten to the second half of the exercise (where I have to have it display about what flower you select) because I cant get this function to work. What am I missing? Also, the exercise we did before these two had us make a very basic account class and object. We don't have to do that at all in this anywhere, but I do know how to do it, in case I need to make a class or something. ANY AND ALL HELP GREATLY APPRECIATED!!! I just don't know what I'm supposed to do, I can't get it to work. Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. .... [Edit] I have moved this thread to resolved since it cannot work the way I want it to (couldn't find a delete button). The variable in question is overwritten each time the function is called and there is no way to cache it globally. I will have to figure something else out for this one. Thank you to those that took a look anyway..... Ok, here is what I have. I am trying to fix up a calculator script that I found online to add a bit more intuitive function to it. I want to use this script but it irritates me the way it is. It's a simple enough script, which is why I want to use it, but I want to be able to use keyboard keys with it (instead of clicking buttons. Here's the HTML: Code: <FORM NAME="Calc"> <TABLE BORDER=4> <TR> <TD> <INPUT TYPE="text" NAME="Input" id="Input" Size="26"> <br> </TD> </TR> <TR> <TD> <INPUT TYPE="button" NAME="one" VALUE=" 1 " OnClick="Calc.Input.value += '1'"> <INPUT TYPE="button" NAME="two" VALUE=" 2 " OnCLick="Calc.Input.value += '2'"> <INPUT TYPE="button" NAME="three" VALUE=" 3 " OnClick="Calc.Input.value += '3'"> <INPUT TYPE="button" NAME="plus" VALUE=" + " OnClick="Calc.Input.value += ' + '"> <br> <INPUT TYPE="button" NAME="four" VALUE=" 4 " OnClick="Calc.Input.value += '4'"> <INPUT TYPE="button" NAME="five" VALUE=" 5 " OnCLick="Calc.Input.value += '5'"> <INPUT TYPE="button" NAME="six" VALUE=" 6 " OnClick="Calc.Input.value += '6'"> <INPUT TYPE="button" NAME="minus" VALUE=" - " OnClick="Calc.Input.value += ' - '"> <br> <INPUT TYPE="button" NAME="seven" VALUE=" 7 " OnClick="Calc.Input.value += '7'"> <INPUT TYPE="button" NAME="eight" VALUE=" 8 " OnCLick="Calc.Input.value += '8'"> <INPUT TYPE="button" NAME="nine" VALUE=" 9 " OnClick="Calc.Input.value += '9'"> <INPUT TYPE="button" NAME="times" VALUE=" x " OnClick="Calc.Input.value += ' * '"> <br> <INPUT TYPE="button" NAME="clear" VALUE=" C " OnClick="Calc.Input.value = ''"> <INPUT TYPE="button" NAME="zero" VALUE=" 0 " OnClick="Calc.Input.value += '0'"> <INPUT TYPE="button" NAME="DoIt" VALUE=" = " OnClick="Calc.Input.value = eval(Calc.Input.value)"> <INPUT TYPE="button" NAME="div" VALUE=" / " OnClick="Calc.Input.value += ' / '"> <br> </TD> </TR> </TABLE> </FORM> Now, what I am trying to fix is the fact that the enter key does not "emulate" the "=" sign button. I did some research and got the following KeyCode script: Code: document.onkeyup = KeyCheck; function KeyCheck(e) { if (document.Calc.Input.value != "") { var formVal = document.Calc.Input.value; } var KeyID = (window.event) ? event.keyCode : e.keyCode; if (KeyID == 13) { alert (formVal); document.getElementById("Input").value = eval(formVal); } } The only key I am concerned with is the enter key (code 13) so i figured I could just fire a statement when that key was detected, however my "formVal" variable seems to disappear after the first if statement. The reason for the first if statement is to keep the "fromVal" variable from being overwritten when the enter key is pressed. As it stands now, the alert box and the form input box display "undefined" when the enter key is pressed. What am I missing here? Hi, firstly I apologise if the title of this thread isn't quite accurate. I'm sure you've all heard it before but I am a complete newbie to Javascript so again: apologies if this is boring and tiresome to even read, let alone help with! I have been asked to make some changes to a form that uses Javascript for the form validation. There is a 'function' that contains the variables of the various form fields and then further code to raise 'alerts' if one of the fields on the form hasn't been filled in. My problem is that for some reason I am unable to add an extra variable to this code after the field of 'County' (this will hopefully make sense when you see the code / link...) and I am stumped as to why. I am able to add variables for all of the other required fields except for 'Postcode' after 'County'. This is the case for both forms. The link is he http://samdelara.co.uk/previews/banq...ation-form.htm and the code I am trying edit is below: function checkAvailibility() { // re-calculate... calculate (); if ( isName() && isAddress1() && isTown() && isCounty() && isPostcode() && isYourEmail() && isFuncDate() && somethingToQuoteFor() && isYourEmailValid() ) { document.ordersummary.emailQuote.value = "No"; setValue(); return true; } else { return false; } } function isName() { if (document.ordersummary.Name.value=="") { alert ("\n Please Enter Your Name") document.ordersummary.Name.focus(); return false; } return true; } function isAddress1() { if (document.ordersummary.Address1.value=="") { alert ("\n Please Enter Your Address") document.ordersummary.Address1.focus(); return false; } return true; } function isTown() { if (document.ordersummary.Town.value=="") { alert ("\n Please Enter Your Town") document.ordersummary.Town.focus(); return false; } return true; } function isCounty() { if (document.ordersummary.County.value=="") { alert ("\n Please Enter Your County") document.ordersummary.County.focus(); return false; } return true; } function isPostcode() { if (document.ordersummary.Postcode.value=="") { alert ("\n Please Enter Your Postcode") document.ordersummary.Postcode.focus(); return false; } return true; } function isYourEmail() { if (document.ordersummary.YourEmail.value=="") { alert ("\n Please Enter Your Email") document.ordersummary.YourEmail.focus(); return false; } return true; } function isFuncDate() { if (document.ordersummary.FuncDate.value=="") { alert ("\n Please Enter Your Function Date") document.ordersummary.FuncDate.focus(); return false; } return true; } function isemailonly() { if (document.ordersummary.emailonly.value=="") { alert ("\n Please Enter Your Email Address") document.ordersummary.emailonly.focus(); return false; } return true; } Any help with this would be very much appreciated and once again, I apologise for my distinct lack of knowledge in this area! Sam Hello. This is very long and I think if you look at code it might be quicker. If not, then please read along. Here is the code and the problem: Code: function addtwoboxes { get values from two text boxes, one about width, the other one about height, and store each in a variable; a=width; b=height checkifwidthproblem(); //to see if the boxes are empty and with numbers checkifheightproblem(); //to see if the boxes are empty and with numbers if (width_not_ok==false && height_not_ok==false) { Go Ahead and do calculations and other things } function checkifwidthproblem() { width_not_ok=false; if problems with the data in the textbox (the a variable is being checked). { bring up an alert box width_not_ok=true; } } //end of checkifwidthproblem function function checkifheightproblem() { height_not_ok=false; if problems with the data in the textbox (the b variable is being checked) { bring up an alert box height_not_ok=true; } } //end of checkifheightproblem function I would like this function to be setup the same way as the addtwoboxes function, but right now I am only calling up the checkifwidthproblem function, and it doesn't execute and the form gets submitted. The fillInvoiceNumber function can be called because if I place only an alert of Hello in it, it comes up, and then the form gets submitted. If it do get this working, I would also need to be sure that it is seeing the results of the variables width_not_ok and height_not_ok, just as they are for the addtwoboxes function. function fillInvoiceNumber() checkifwidthproblem(); //to see if the boxes are empty and with numbers checkifheightproblem(); //to see if the boxes are empty and with numbers if (width_not_ok==false && height_not_ok==false) { Go Ahead and do calculations and other things ] This is going to be a bit long, but it's the only way I can be sure of that I have covered everything, so please bear with me and help me out. Thanks. Please Provide Solution Using my way First, Then suggest Better Ways: O.k. Before I post the problem, I know, since I took program classes years ago and since I have done a little research here and here, that there are better, more efficient, and tidier ways to do what I am doing, but I have started already this way and would like to continue this way. I will ask what's the better way to do this in another thread, unless 1) you feel like explaining the bettery way and 2) it's not too long or complicated, but AFTER you have provided me with a solution to doing it my way. The Setup / What My Form is Supposed to Do: I have a form with two buttons. The user has to enter some information into the form and then click the button to have some calculations done and for other text fields to automatically filled in. After that, the user has to click submit. A note about the submit button: The type is image and the name says submit. The form line has the following: <form target="abcco" action="https://www.domainname.com" method="post" id="Form" onsubmit="fillInvoiceNumber()"> I will explain what the fillInvoiceNumber() is doing later on. Data Validation / Verification: 1) I want to ensure that when the user clicks the first button, let's call it GetPrices to make things easier, that it checks to see if data is enterted into the textboxes and that it is the right kind of data. 2) After the GetPrices button is clicked, the user can then enter nonsense into the textboxes and click submit or, never click the GetPrices button, the first button to begin with, and so junk will be submitted. This is what I have going on: For the GetPrices button, I have the following: onclick="addtwoboxes() (the names I have aren't fully descriptive of all that's going on, as I do have more things happening, but for now I have left them like that). in the addtwoboxes function I have it calling up two functions, each for a textbox in which the user has to enter width in one and height in another, and if the textboxes are not empty and have the correct data in them, then the calcuations for the addtwoboxes take place; if not, nothing happens (regarding the calculations; an alert box comes up for either or both of the functions in the addtwoboxes function if something is wrong). So, the two functions that are called in the addtwoboxes() function are checkifwidthproblem() checkifheighthproblem() which I am calling just like that but with a semicolon to the end of each one. This next now is one of the areas where I do believe this can be combined, since only one value is changing, but I will leave it like this for now. The checkifwidthproblem() function starts of with a variable:width_not_ok=false; (after doing some research, I see that this is often set the opposite way or not set at all) if something is wrong with the data entered into the width textbox, an alert box with a message comes up, and I then have the following variable: width_not_ok=false; For the checkifheighthproblem(), it's basically the same as the width problem, except, with it's own set of variables. I had the same ones as the width one, but if things were not ok with the width textbox, but o.k. with the height textbox, the calculations were taking place. So, because of this I used new variables in the height function and had an if statement check both variables for false. So, the checkifheighthproblem() starts of with the variable: height_not_ok=false and if there is a problem with the data entered into the height textbox, an alert box comes up and the variable height_not_ok=true is set. When the user presses the GetPrices button, this function works excellently. Everything goes as it should. The problem is when the form is being submitted. I would like the textboxes to be rechecked. So, right now I have a function called fillInvoiceNumber() in which it is joining two strings together after getting their values from a drop down menu. This has to be done at the time of submission only for the page that's processing the results to have them interpreted the way I want it to. Prior to joining those strings, I would like it check and see if everything is o.k. with the two textboxes by calling the two functions of that check height and width and if they are not, for the alert boxes to come up, for the joining of the strings to not take place, and for the form to not be submitted. However, the fillInvoiceNumber() function is not executing either function at all. If it does work, I would also need to be sure that it is seeing the results of the variables width_not_ok and height_not_ok. Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Hey guys, I'm new to jquery and I'm sure this is a VERY simple problem.. Here's my code Quote: <style type="text/css"> #box { background: red; width: 300px; height: 300px; display: none; } </style> <script type="text/javascript"> $(function() { $('a').click(function() { $('#box').slideDown(4000); }); }); </script> </head> <body> <div id="box"></div> <a href="#">Click Me!</a> </body> </html> As you can see it's pretty simple, I've made the box slideIn. My problem is I want to make a separate button to slide it back out, but because I've used the "a" tag it's associating all links with the same function, how do I get around this? I'm sure it's really simple! Thanks Hi all, I'm pretty new to javascript coding and was trying to make a fading image slideshow. i have found one on dynamicdrive modified it, all looks fine. The first image shows and thats it. doesnt go through the photos :/ probably something simple but i cant work it out, any thoughts? EDIT: Code: <head> <script language="javascript1.1"> var mygallery=new fadeSlideShow({ wrapperid: "column2", dimensions: [250, 180], imagearray: [ ["images/img1.png"], ["images/img2.png"], ["images/img3.jpg"] ], displaymode: {type:'auto', pause:2500, cycles: 10, wraparound:false}, persist: false, fadeduration: 500, descreveal: "ondemand", togglerid: "" }) </script> </head> <body> <div id="column2"><a href="#" class="next"><img src="images/img1.png" name="slide" id="rounded-image" height="288" border="0" style="filter:blendTrans(duration=3)" alt="image-1"/></a></div> </body> Thanks, Storm08 Hello, Just trying to combine php variable with some javascript in a simple if ... else. This is the script code in php: Code: <script type="text/javascript"> var the_rad_val=<?php echo $N_rad_val;?>; if (the_rad_val.value='n') { function removeLink(); } else { function restoreLink(); } </script> This is how it looks in the browser (source) Code: <script type="text/javascript"> var the_rad_val=n; if (the_rad_val.value='n') { function removeLink(); } else { function restoreLink(); } </script> The 2 functions a Code: function removeLink() { document.getElementById("mydiv").style.visibility = "hidden"; } function restoreLink() { document.getElementById("mydiv").style.visibility = "visible"; } // end function Guess I did something wrong because the "mydiv" is visible when it shouldn't be Can someone help me out as I am not too good with javascript . Thank you. . |