JavaScript - New To Calling Functions? (easy)
i have a script that will let you know what the date is.. as well as a countdown to thanksgiving.. it is called tday.js
Code: function showDate() { thisDate = new Date(); var thisWDay=thisDate.getDay(); var thisDay=thisDate.getDate(); var thisMonth=thisDate.getMonth(); var thisYear=thisDate.getFullYear(); var mName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"); var wdName = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return wdName[thisWDay]+", "+mName[thisMonth]+" "+thisDay+", "+thisYear; } function calcThanksgiving(year) { var delta = year - 1900; var tday = delta % 12; tday = (tday + Math.floor(tday/4) + Math.floor(delta/12)) % 7; return (tday == 0)? 28 : (29 - tday); } function daysToThanksgiving() { var thisDate = new Date(); var year = thisDate.getFullYear(); var tday = calcThanksgiving(year); var tdate = new Date("November "+tday+", "+year); if (thisDate > tdate) { year++; tday = calcThanksgiving(year); tdate = new Date("November "+tday+", "+year); } return Math.floor((tdate-thisDate)/(1000*60*60*24)); } so now i have to call upon this script to print "today is ..the date.. . <br> there are ..days... till thanksgiving im kind of new of calling on javascript files but i came up with Code: <SCRIPT LANGUAGE="JavaScript" SRC="tday.js"> </SCRIPT><script type="text/javascript"> document.write('Today is: '+showDate()+'. There are '+daysToThansgiving()+' days until Thanksgiving.'); </script> and it doesnt seem to be working. Similar TutorialsHi, I'm very new to Javascript and I need some help on calling some existing functions. What i want to do is create a new function to call the first test1 and then call test2 to turn on the checkbox. i hope this isn't confusing. Code: function test1(inStore,onSale,newItem) { var daURL; if (inStore==true) { BSSetStoreOnly(true); daURL="s-2-Online-Store.aspx?ms=bsm1"; if (onSale==true){ daURL+='&SaleOnly=1'; } } else { BSSetStoreOnly(false); daURL="s-1-Our-Products.aspx?ms=bsm1"; if(newItem==true) { daURL+='&NewOnly=1'; } } location=daURL; } function test2() { var pInc; chk=document.getElementById("chkAll"); pInc=readCookie("overrideURL"); if (pInc==null) { pInc=0; } if (pInc==0) { chk.checked=false; } else { chk.checked=true; } } function callingTest1Test2 { } I'm coding a simple random sentence generator & this is the beginning part of what I'm trying to accomplish. I created 3 different functions with 3 separate buttons & 3 separate text areas to display the noun, verb, or article once the button is pressed. However, when I press a button, nothing shows up in the text area! Can someone please tell me what I'm doing wrong & give me a fix? It has to be a simple problem, but I am very very new to this & need help. Thanks in advance! Code: <?xml version="1.0" encoding="ISO-8859-1"?> <!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 language="JavaScript"> function noun() // Assumes: nothing // Returns: a random noun { return RandomOneOf(["man", "woman", "ball"]); } </script> <script language="JavaScript"> function verb() // Assumes: nothing // Returns: a random noun { return RandomOneOf(["hit", "liked", "smelled"]); } </script> <script language="JavaScript"> function article() // Assumes: nothing // Returns: a random noun { return RandomOneOf(["the", "a", "some"]); } </script> </head> <body> <input type="button" value="Noun" onclick="document.getElementById('OutNoun').value = noun();" /> <TEXTAREA ID="OutNoun" ROWS=1 COLS=15 WRAP VALUE=""></TEXTAREA> <input type="button" value="Verb" onclick="document.getElementById('OutVerb').value = verb();" /> <TEXTAREA ID="OutVerb" ROWS=1 COLS=15 WRAP VALUE=""></TEXTAREA> <input type="button" value="Article" onclick="document.getElementById('OutArticle').value = article();" /> <TEXTAREA ID="OutArticle" ROWS=1 COLS=15 WRAP VALUE=""></TEXTAREA> </body> </html> Hi, I have an embarrassingly similar problem to the last time I was here. I have a google map that generates links and checkboxes from an xml file and puts them in a sidebar. The links open infowindows and the checkboxes show or hide lines on the map. Which all works ok. But (like last time) I have another function that puts arrowheads along those lines to indicate directionality. The code which turns the lines off and on looks like this: Code: function togglePoly(poly_num) { if (document.getElementById('poly'+poly_num)) { if (document.getElementById('poly'+poly_num).checked) { gpolys[poly_num].show(); } else { gpolys[poly_num].hide(); } } } and the sidebar creation code is like this: Code: sidebar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />'; so I was thinking that I could just call the functions that put the arrows on the lines like this, to show/hide them along with their respective lines: Code: function togglePoly(poly_num,category) { if (document.getElementById('poly'+poly_num)) { if (document.getElementById('poly'+poly_num+category).checked) { gpolys[poly_num].show(); show(category); } else { gpolys[poly_num].hide(); hide(category); } } } and change the sidebar code to this: Code: sidebar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+','+category+');">' + label + '<br />'; and all would be well. But all is not well - I get an error saying that my category is not defined in the sidebar_html line. If you want to see it in action, here's without trying to toggle the arrows on and off: http://xelawho.com/map/busroutes2.htm and here's the version with the category undefined error: http://xelawho.com/map/busroutes3.htm can anybody help me out here? thanks in advance. Hi, I would like to do something like this: Code: function searchLocations(count) { var found = false; var input = document.getElementById('autocomplete').value; var inp = input.toLowerCase(); var count = 0; for (var j = 0; j < gmarkers.length; j++) { gmarkers[j].hide(); var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); count++; } } if (count==1) myclick(j); if (count>1) centerZoom(); if ( ! found ) alert("No matches found. Please check your spelling or refine your search."); } on this page here, but the functions - myclick(j); and centerZoom(); aren't getting called. I tried it with switches here, but that only made things worse. I know the functions work because if I put them two } up, they get called, but that takes them out of the if statements. Those if (count...) statements have to be where they are so that "count" will get the right value. Any ideas? Hello all here is a more intelligent question. This one is just on an exercise I am doing. I have to call a function using parameter values. my main function is this Code: function showResults(race,name,party,votes) or just function showResults in the next lines below i have to call the function is this the right way Code: <script type="text/javascript"> { showResults=("race[0],name1,party1,votes1"); } </script> or should it be without the { and } like this? Code: script type="text/javascript"> showResults=("race[0],name1,party1,votes1"); </script> or is it like this Code: script type="text/javascript"> showResults(race[0],name1,party1,votes1); </script> Thanks all, what would be the proper method Thanks Hello, so I'm trying to call multiple functions with onClick. It doesnt really work, just wondering why. Advice or tips would be nice, thank you guys for your time. By the way this is a project for school so the comments are for my professor Code: <head> <title>Untitled Document</title> <script type="text/javascript"> //hello, this code doesn't work, I did it piece by piece so the bits work, but when I combined them, it stopped working function texter(newText){ var oldHTML = document.getElementById('outputPrompt').innerHTML; document.getElementById('outputPrompt').innerHTML = newText+"<br />"+oldHTML; console.log(newText); } // texter function from class function menuMain(){ var userInput = document.getElementById('input').value; var mainMenu; if (userInput == "3"){ mainMenu = menuThree(); } else if (userInput== "2") { mainMenu = menuTwo(); } else if (userInput== "1") { mainMenu = menuOne(); } texter(mainMenu) } //going to the functions by calling them function menuOne(){ var userInput = document.getElementById('input').value; if (userInput.length == 0){ texter("You need to enter something in the input box"); } else { texter("the string has been saved"); } } // if the length is equal to zero then there was nothing inputted function menuTwo() { var userInput = document.getElementById('input').value; var theArray = userInput.split(/\s|\n|\r/); //split string into words array i looked up the regex on coding forums //also had help to create this from coding forums var WordsFound = [i]; for (var i=0; i<theArray.length-0; i++) { if (theArray[i].length < 5) { WordsFound.push('eep- '+theArray[i]); } else { if (theArray[i].length > 5) { WordsFound.push(theArrray[i]+' -zzz'); } else { WordsFound.push(theArray[i]); } } } document.getElementById('outputPrompt').innerHTML = WordsFound.join('<br>'); } // if the array length is less than five the word will push it onto the array // vise versa with the array length being more than five //then i join the word with the array function menuThree() { var userInput = document.getElementById('outputPrompt').reset(); } //reset the output function combineFunctions() { menuMain(); menuOne(); menuTwo(); menuThree(); } // combining the functions into one function so i can call it on onclick function cleartext(){ document.getElementById('input').value=""; } </script> </head> <body> <h1>RoboSpeek</h1> <textarea type='text' id='input' onfocus="cleartext()" cols="40"rows="10" wrap="physical"> Please enter 1,2,3 or Exit</textarea><br /> <input type='button' onclick='combineFunctions()' value='submit'/> <p id='outputPrompt'>Please enter 1,2,3 or exit only</b> </p> </body> </html> i now have <a href=""javascript:NewCssCal('repaymentdate','ddMMyyyy')""> how can I have this after it calls teh newcsscal and fills in the textbox call another function. (i don't want to add it to newcsscal as that's used in multiple locations and I only need to call this function in 1 location. I am currently designing a table as such Code: ___________________________ | TABLE | | | FRAME A |___________________________| | last row clicked | FRAME B |___________________________| the top frame is a table and the bottom frame contains the last row clicked called through onclick. question: if frame B is a php file with a javascript object, how do i call the javascript object's function to print the data? here is what i have so far index.html //this is the source code for the site Code: <html> <frameset rows = "60%, 40%"> <frame src = "table_driver.php" name = "A" id = "FRAME1"> <frame src = "bottom_row.php" name = "B" id = "FRAME2"> </frameset> </html> printJSTable() //prints the table shown in frame A Code: function printJSTable() { echo '<script src = "java_script.js"></script>'; echo '<script src="sorttable.js"></script>'; echo '<table class = "sortable" id = "myTable" border = "1">'; echo '<thead id = "header"><tr>'; foreach($this->columns as $header => $order) { echo '<th>'; echo $header; echo '</th>'; } echo '</tr></thead><tbody>'; $counter = 0; for($i = 0; $i < $this->numRows; $i++) { //IMPORTANT changeRow(this) is JS call echo '<tr onclick = "changeRow(this)" onmouseover = "mouseOver(this)" onmouseout = "mouseOut(this)">'; foreach($this->data[$i] as $key => $value) { echo '<td>'; if($value!="") echo $value; else { echo ''; } $counter++; echo '</td>'; } echo '</tr>'; } echo '</tbody></table>'; echo '<form><input id = "'.$this->numRows.'"type = "button" value = "add row" onclick = "addRow(id)"></form>'; } and this is changeRow(this) which is supposed to create the table in frame b Code: //populates headersArr and rowArr correctly parent.B.obj = new TableData(headersArr, rowArr); parent.B.obj.printTable(); here are the function definitions for TableData Code: function TableData(headers, row) { this.headerArr = headers; this.rowArr = row; } TableData.prorotype.printTable = function() { for(i=0; i<this.headerArr.length; i++) { document.write('<tr><th>'); document.write(this.headerArr[i]); document.write('</th><td>'); document.write(this.rowArr[i]); document.write('</td></tr>'); } } and then, finally, this is the php file for the bottom frame Code: <html> <head> <link rel = "stylesheet" type = "text/css" href = "style.css"/> <script type = "text/javascript" src="java_script.js"></script> </head> <body> <script> obj = new TableData; </script> </body> </html> what i want to do is populate the variable obj from ^ (bottom_row.php) and then use the print function to print it out. right now it is populating correclt,y but i cant get it to print. The error console says that Value undefined (result of expression parent.B.obj.printTable) is not object. ?? sry for all the code! just didnt want to leave anything out thanks! Hi, i was wondering if there was a way to call a nested javascript function directly, from outside of the function its nested in? for example, if i have the following functions: Code: <script type="text/javascript"> var test = function(){ var testInner = function(){ alert('testInner'); } } </script> can i then call the 'testInner' function directly from an onclick action something like this: Code: <a href="#" onclick="test.testInner()">TEST JS</a><br /><br /> That code is obviously not working for me, but is there something similar to what ive shown here that will work? Thanks in advanced I still can't understand very well when to use and when NOT to use parenthesis when calling/using methods and functions. Case 1: Where I commented "// No parenthesis.", could someone explain why not. And at the end, where the commen reads "// Parenthesis. ? Code: /* This function will be used as a method inside the objects. */ function getPayment() { thePayment = 250; thePayment += (this.seats == 'leather') ? 100 : 50; thePayment += (this.engine == 'V-8') ? 150 : 75; thePayment += (this.radio == 'CD Player') ? 30 : 10; return thePayment; } /* Object Constructor (prototype of the object). */ function car(seats, engine, radio) { this.seats = seats; this.engine = engine; this.radio = radio; this.payments = getPayment; // No parenthesis. } /* Creates an instance called 'my_car' out of the 'car' object. */ var my_car = new car('cloth', 'V-6', 'Tape Deck'); /* Object Initializer - automatically instantiates the object. */ var carObj = { seats: 'leather', engine: 'V-8', radio: 'CD Player', payments: getPayment // No parenthesis. No comma after last item. } // Firebug... console.log(my_car.payments()); // Parenthesis. console.log(carObj.payments()); // Parenthesis. /* vim:set foldmethod=indent: */ Case 2: Please look at the comments. Code: window.onload = initAll; // Why no () here? function initAll() { window.doStuff(); // Why () here? } function doStuff() { var msg_text = 'I love you so much!'; var msg_link = window.document.getElementById('msg_link'); console.log(msg_link); var msg_box = window.document.getElementById('msg_box'); msg_link.onmouseover = function() { //msg_box.value = msg_text; msg_box.setAttribute('value', 'May the force be with you!'); }; msg_link.onmouseout = function() { /* This works in ie. */ //msg_box.value = ''; /* Doesn't work in ie7 (and probably not in ie6 either). * Perhaps the code above is reasonable. */ msg_box.removeAttribute('value'); } } /* vim:set foldmethod=indent: */ Hello, Our website is built in ASP.NET and uses a content management system. The CMS came with a wealth of JavaScript files and I decided to use one of these files for form validation. Although the file is over 2,300 lines, from what I can tell it is supposed to return true if the form is valid and false otherwise. The problem is that a function inside that file seems to get to a certain point, and somehow quit and return true no matter if the form is valid or not. I am calling this JS from an ASP.NET button control. When the button is clicked, a JS function ValidateForm(document.forms[0]) is called. My ValidateForm function calls another function inside the JS file (which calls another, and another...). No matter what, when that second function is called and executed, code execution stops at some point and the form submits (postbacks). I can see that the validation is working just before the postback, but it is not preventing the form from being submitted, and it also stops executing any code after it. Here is my code: ASP: Code: <asp:Button ID="SubmitBtn" runat="server" Text="Submit Form" CausesValidation="false" CssClass="submit_button" OnClientClick="FmValidate(document.forms[0]); return false;" OnClick="SubmitBtn_Click" /> My Javascript: Code: function FmValidate(formObj) { var strError = ''; var e = null; if (strError == '' && 'function' == typeof design_validateHtmlForm) { alert('before'); // this line causes execution to stop - located in external JS file // code states "Returns first invalid element, or null." e = design_validateHtmlForm(formObj); alert("e is " + e); if (e) { strError = e.title; } return false; } } In my ASP.NET button, changing the OnClientClick method to "return false" will prevent form submission, but "return FmValidate(formObj);" will not if that function calls design_validateHtmlForm(formObj). I receive the message box saying "before" but I never receive the second one. I have debugged using Fire bug, but the code seems to cycle through each element on the page and stepping through the code is not realistic (I have done so for 20-minute stretches). I am wondering if anyone has any ideas what code I could look for that would stop execution and return true no matter what, or how I could begin debugging this monster. so, I can pass a value from a select list to another function which then decides which function to call, but I want to cut out the middleman, and make the values the function calls, and call them directly on the onchange... I imagine something like this: Code: <select id="select" onchange="this.value"> <option selected value="function1()">Funtion 1</option> <option value="function2()">Function 2</option> <option value="function3()">Function 3</option> </select> is it possible? Short version at bottom Need to add an array before an array to init thousands of arrays. Mostly worked out, just need to add an array before an array. ........Please check it out. Really want to finish this tonight or tomorrow. Alright, so two days later I finally have this portion working but its only because of the awesome people of this forum and unforunately these people thought I had some half decent grasp of javascript (which I don't) and so their answers were meant to solve my problem but each time I was left with no idea how to repeat what they did. So, I've learned a lot of extra stuff that I really could have done without in the effort to try and understand what they did. This is all well and good because I'm much farther than I am had I gone it alone (so thank you!) but please, anyone that posts an answer, could you try and explain a bit of how I might use your solution again. For example, today I was confused for about an hour because I didn't understand how [CODE]var newArray=[], a, i=0;CODE] worked but only after staring at it long enough and not finding anything on google related to "values inputed after array initialization" did I finally realized that these were not params of a new array but just new variables. Code: var alphabetArray =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','all1']; var a; var i=0; while(a=alphabetArray[i++]){ eval('var _img_'+a+' = []'); eval('var _h_'+a+' = []'); eval('var _r_'+a+' = []'); eval('var _m_'+a+' = []'); eval('var _yt_'+a+' = []'); } alert(_h_all1) and its working perfectly but I somehow I need to add Code: var pageNum = ['','p2_','p3_','p4_','p5_','p6_','p7_','p8_','p9_','p10_'] need to add pageNum to every alphabetArray so... _img_a = [],_img_p2_a = [], img_p3_a = [].... _img_p10_a = [] repeated for every variable in alphabetArray. _yt_p10_all1=[] Super short version Code: var alphabetArray =[letters/numbers]; var a; var i=0; while(a=alphabetArray[i++]){ eval('var _img_'+a+' = []'); } // works now I need to add 10 page prefixes before each var in alphabetArray Code: var pageNum = ['','p2_','p3_','p4_','p5_','p6_','p7_','p8_','p9_','p10_'] need to add pageNum to every alphabetArray so... _img_a = [],_img_p2_a = [], img_p3_a = [].... _img_p10_a = [] repeated for every variable in alphabetArray. _yt_p10_all1=[] Please explain how this might be possible in a way that your dog might understand. 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. 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 im trying to make something that selects two different images but it keeps selecting two images that are the same, and dont know how to go about it to make it select two different. please help Code: <!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/javascript; charset=utf-8" /> <title>Untitled Document</title> <script language="JavaScript"> <!-- var theImages = new Array() theImages[0] = '100.jpg' theImages[1] = '200.JPG' theImages[2] = '300.JPG' theImages[3] = '400.jpg' var j = 0 var p = theImages.length; var preBuffer = new Array() for (i = 0; i < p; i++){ preBuffer[i] = new Image() preBuffer[i].src = theImages[i] } var whichImage = Math.round(Math.random()*(p-1)); function showImage(){ document.write('<img src="'+theImages[whichImage]+'">'); } //--> </script> </head> <body> <div align="center"></div> <table width="996" height="511" border="1"> <tr> <th scope="col"><script language="JavaScript"> <!-- showImage(); //--> </script> or <script language="JavaScript"> <!-- showImage(); //--> </script> </th> </tr> </table> </body> </html> I have written the following code which returns a simple times table. The problem is that I want the resulting times table written to the div id=results section in the body of the html page rather than writing it to another page. I hope that makes sense! Thanks in advance for any help. <html> <head> <script type="text/javascript"> function timestable() { var num = parseInt(document.timesForm.times.value); var counter = 1; while (counter<=12) { document.write(counter+" X "+num+" = "+counter*num+"<br />"); counter++; } } </script> </head> <body> <form id="timesForm" name="timesForm"> <p>Enter the number he <input type="text" id="times" /></p> <p> <input type="button" value="Show Times Facts" onclick="timestable()" /> </p> <div id="results">Times Facts</div> </form> </body> </html> I am just learning javascript. I am playing around with different html elements and document.write. I have a HTML page with elements h1, h2, h3, and h4. I want to write something (in this example "found it") next to the elements. <head> <script type="text/javascript" language="javascript"> var headerList = getElementsByTagNames('h1,h2,h3,h4'); if (headerList) { document.write("Found it!"); } </script> </head> <body> <h1> </h1> <h2> </h2> <h3> </h3> <h4> </h4> </body> Why doesnt this work? I am assuming my logic is flawed? This is javascript that turns your current url into a tinyurl. How would I go about getting this to open into a new tab instead of the same tab? Code: javascript:void(location.href='http://tinyurl.com/create.php?url='+encodeURIComponent(location.href)) |