JavaScript - Newbie Question About Functions + Variables
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. Similar TutorialsHi Everyone I am trying to write some code to create an object in JS that contains the x,y coords for a shape i wish to draw. I create the shape, and then in a draw function I draw the shape to the screen from the object I created erlier. Trouble it is does not seem to work :S have anyone got and ideas? Code: var myShape = new newShape(200,200); function init() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); return setInterval(draw, 50); } // init function newShape(x,y){ this.un_X=x this.un_Y=y function drawAll() { ctx.beginPath(); ctx.arc(un_X,un_Y,30,0,Math.PI*2,true); ctx.closePath(); ctx.stroke(); } // drawAll } // newShape function draw() { ctx.clearRect(0, 0, WIDTH, HEIGHT); myShape.drawAll(); } // draw init(); Thanks in advance Hi! I'm as new as they come when it deals with website development but forums have been useful to me in the past and I'm hoping I can get some kind of direction from all the wonderful people on this forum! I have an idea for a website that I'd like to pursue, and it would need functions such as: -Live news feed -Member logins, profiles, ability to rate/leave feedback for members -Mobile phone friendly -Comment on postings -Create an intro video (maybe even with animated stick figures to explain how the site works) -Accept paypal or other payment method -And basically, need to understand the monthly maintenance cost of all these functions, how to minimize expenses, etc. I know it seems far fetched for a newbie! But I need to know if this is possible.. how would I begin implementing a site like this.. Do I need to find a programmer to code it from scratch? Are there pre-written scripts available for all the functions I listed? What can I expect the costs to be? What's the best way to move forward? 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, 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 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> 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 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] 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 learn javascript and I found codecademy.com which seems like a great way to learn the language. Before the first lesson it says Quote: You should be comfortable with loops, if statements, functions, and objects before attempting this course. Can someone explain what these are or point me in the direction where I can find the answers? I tried searching with google, but I havent found anything that clearly states what exactly the loop, object, etc. is. Thinking in Objects 4 objects w/constructors/overloads min 3 properties on each min 3 methods total was just wondering if anyone had any good links or tutorials to get me started on my first javascript assignment I'm in a computer coding class, and I'm having a bit of trouble with Javascript. I'm not looking for anyone to do my homework for me, but any hints you could give me as to why this code isn't working would be greatly appreciated. Basically, I need an empty text box where the user enters their guess as to my age. The user enters their guess, and then gets an answer as to whether their guess is right, too high, or too low. The page looks right, but I can't get the function to work. Thank you... <html> <head> <script> function howoldami(age) if(age=23) { alert("You guessed right!"); } else if { (age>23) alert("I'm not that old."); } else { alert("I'm not that young."); } </script> </head> <body> <form> Guess My Age!<input name="age"><br> <input type=button value=Guess! onclick="howoldami(age.value)"> </form> </body> </html> This is what I am aiming for. I want to be able to click on a word that would then write text in a specified area. This is what I came up with but it writes it at the top of the page and only for a moment then disappears.... These are my clickable words Code: <a href="#textarea" onClick="MathHomework('W2')">Week 2</a> <a href="#textarea" onClick="MathHomework('W3')">Week 3</a> the anchor named 'textarea' is where I want the output to be written which is placed on my html page. This is my newbie script Code: <script type="text/javascript"> function MathHomework(week) { if (week == "W2") document.write("<p>Review Chapter Twelve</p>"); else if (week == "W3") document.write("<p>Final Chapter Review Test</p>"); } </script> <a name="textarea"> (text area for javascript output)</a> so is my onclick syntax wrong maybe? and yes I have read rule#5 and I am trying to understand my mistakes. Thank you in advance Hello, I'm in the process of getting a better understanding of javascript (instead of just copying and pasting JQuery script onto my site). So I have a(dumb?) question. Can I name a var what ever I want? For example, var car_name("Ford Escape"); Or am I misunderstanding this? THanks. Hi Everyone I'm learning Javascript with varying degree's of success but am very much in the early phase. My question/problem is this: [ICODE]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <script language="javascript" type="text/javascript"> var degFahren = new Array(212, "string data", -459.67); var degCent = new Array(); var loopCounter; for(loopcounter =0; loopCounter <= 2; loopCounter++){ if(isNaN(degFahren[loopCounter])){ alert("Data " + degFahren[loopCounter] + " at array index " + loopCounter + " is invalid"); continue; } degcent[loopCounter] = 5/9 * (degFahren[loopCounter] -32); } for (loopCounter =2; loopCounter >=0; loopCounter --){ document.write("Value " + loopCounter + " was " + degFahren[loopCounter] + " degrees Fahrenheit"); document.write(" which is " + degCent[loopCounter] + " degrees centigrade<br />"); } </script> </body> </html> /ICODE] The following code does not return any errors in my browser but I'm confused since I'm sure I should be seeing an alert box telling me that there is invalid data entered bu this doesn't happen, also as far as I can make out I should only be receiving an error for the 2nd loop but there seem to be an error message returned for all 3 loops?? This is all possibly correct but I'm learning from a book and I have no-one to ask these mundane questions to. Any help would be greatly received. Sara Hi! Im new to the world of javascript, so bare with me. It might be a stupid question but i got a input form, i know how to get the data in but i need to single out one of the numbers. the input looks like: xxxxxx-xxxx I've tried almost everything that i can think of... A nudge in the right direction would be appreciated. I've had several problems with document.getElementById() and haven't been able to find a reason for this. I've searched these forums and I'm sorry if I've still managed to miss if there's an answer to this, as it seems to me to be a basic question. When I use getElementById() it keeps returning as 'undefined' in both FF och IE. I've had to use getElementsByName() instead, and since I only have one element, I have to write element[0] to make it work which seems rather redundant. This is parts of my JS code: Code: var postName = document.getElementsByName("postName"); //getElementById doesn't work here var postText = document.getElementsByName("postText"); //...nor here. if (postName[0].value == "" && postText[0].value == "") { document.getElementById('feedback').innerHTML = "Some text."; //For some stupid reason getElementById works here! } And the HTML looks somewhat like this: Code: <div class="addName" id="addName"> <input type="text" name="postName" id="postName" class="textBox"></input> </div> <div class="addText" id="addText"> <textarea class="textarea" name="post" id="postText"></textarea> </div> <div class="feedback" id="feedback"></div> I don't see why it wouldn't work, but this isn't the only time it's happened so I must be missing something. Anyone who can enlighten me as to what that is? Hi, I'm just starting out with a few bits of javascript and have hit a problem. The story is this: I have a basic HTML page that I want to display using a different css file depending on the page that the request comes from. I though I'd do this by appending "?cs=a" or "?cs=b" depending on the calling page. My problems are occuring whilst trying to read the data in the URL (querystring?) The code below is meant to be a bit of a debugger sort of affair in that it should display the variables but for the life of me I can't get it to work. The problem is that none of the variables seem to be getting populated with data, therefore nothing is displayed on the page and no css file is loaded. I'm pretty sure its something relatively simple so would appreciate if an expert could cast their eye over what I have below and point out the error of my ways... Code: <%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <SCRIPT type="text/javascript"> var thequerystring = new String(Request.QueryString("cs")); if (thequerystring == "a") { cssfile = "css1.css"; } if (thequerystring == "b") { cssfile = "css2.css"; } document.write('<link href="'+cssfile+'" type="text/css" rel="stylesheet">'); </SCRIPT> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <p><span class="texttype">hello</span></p> this should change the format of the text depending on the css file that was loaded... in theory!! <p> </p> <p>Here is a list of the variables and their values... <script type="text/javascript"> document.write('<b>Some variables...</b><br>'); document.write('cssfilename: '+cssfile+'<br>'); document.write('Querystring text: '+thequerystring+'<br>'); </script> </p> <a href="javascript: history.go(-1)">Back <-- </a> </body> </html> Many thanks in advance Dan I have yet to have my ah-ha moment with Javascript but I think its coming soon. there are small things that seem to be baffling me and Im hoping posting to the forums to get help from people of limitless wisdom. What exactly does the "|" mean in this code? or I should say what does it do? Code: document.template.Aprod_string.value = document.template.Aprod_string.value + "|" + string_recode(Aprod_array) ; Hi, I am just beginning out with Javascript and trying to complete a simple login page. Clicking on the Login button should bring up a message 'Access authorised' or 'Access denied' in the 'output' div of the page. Unfortunately only 'Access Denied' displays, even if the password entered is correct. There are no messages displayed in the Error Console. Any advice greatly appreciated! Code: <html> <head> <title>Function Example</title> <script language="javascript" type="text/javascript"> function isAccessAuthorised(enteredPassword) { var result; if(enteredPassword=="password") { result=true; } else { result=false; } return result; } function buttonClicked() { var isAuthorised = isAccessAuthorised("enteredPassword").value; if(isAuthorised==true) { document.getElementById("output").innerHTML=<p>Access authorised</p>; } else { document.getElementById("output").innerHTML=<p>Access denied</p>; } } </script> </head> <body> <form> <input type="text" id="username" /> <br/> <input type="text" id="enteredPassword" /> <br/> <input type="button" onClick="buttonClicked()" value="Login"> </form> <div id="output"> </div> </body> </html> |