JavaScript - Built In Functions
I am having difficulty with the isNaN built-in function. Here is the code that I have written, with the event handler onchange, the function does not return the desired response. Any information would be appreciated...
function checkNumber(fieldValue) { var numberCheck = isNaN(fieldValue); if (numberCheck == true) { window.alert("You must enter a numeric value!"); return false; } } Here is an example of the event handler code...one of three calls to this specific function... <input type="text" name="zip_billing" size="5" maxlength="5" onchange=" return checkNumber(this.value);" /> Similar TutorialsHi all, I was following this tutorial for a jquery based scroller but I am having some problems: http://www.webdesignbooth.com/create...carousel-lite/ When it loads the block starts out as I want it then suddenly squeezes down and chops the text? The area in question is 'Featured Employers' http://www.beta.educationvacancies.com/index.php Can anyone advise? many thanks, greens85 I am building iframes from database entries. Is it possible to resize them with an onclick event?
Hello everyone, i hope your good. I decided when redesigning my website that i would try and build nearly everything in it by hand, which included a nice Javascript slideshow. While coding it (coded on Windows 7 and Vista) I ensured i checked it compatability with Firefox, IE, Chrome and Safari. From what i could tell everything was working good (except for some endless looping problems but lets ignore that for now). It even worked on the iPhone browser. But i sent it to a friend to test and they said nothing was working, after some discussion i descovered they were using IE7 (i was testing in IE8). From what i can see, IE7 has some problems with nested .appendChild and general document handling. I had tried to do my best keeping to using objects in javascript and now just writing HTML, and on one side it worked as it works on most browsers, but not IE7. The page it can be tested on it: http://xvolt.x-volt.com/downloads/view.php?id=3 And the code itself is: http://xvolt.x-volt.com/js/slideshow.js The code is nearly all based in a class, but i kept finding problems so there are a few functions found outside the class. The area where most things go wrong is in the function: this.goToImage = function (image) { As this is used to generate the floating div above all the content. This function also uses IMG objects which are hidden until the image has loaded (instead showing a nice please wait logo) and then once loaded it appears. I have tried using .innerHTML to get around the append child problems but the images dont seem to work the same as just passing object around. If anyone has any tips to get around this would be awesome as this little self project has seemed to become harder then i thought! Thanks Simon Hi all, I am looking for a script that I can only describe. Often, in facebook, when a new window opens there is only the first few lines of text visible followed by a few dots with an invitation to "read more". Once clicked the additional text expands and becomes visible. I don't even know what this behavior is called so it's hard to get started. Any help or pointers in the right direction will be much appreciated. Anita. Cape Town. I am trying to add tabindex values to buttons built in JavaScript as I did with accesskeys but having no luck--it disrupts my page layout. Anyone have suggestions? Here is the code I am working with: Code: function ObjButtonBuild() { this.css = buildCSS(this.name,this.x,this.y,this.w,this.h,this.v,this.z) this.div = '<' + this.divTag + ' id="'+this.name+'" style="text-indent:0;"></' + this.divTag + '>\n' this.divInt = '<a name="'+this.name+'anc" href="javascript:void(null)"' if(this.accessKeyValue && this.accessKeyValue!=null){ this.divInt+=' accessKey='+this.accessKeyValue+' '; } if( this.altName ) this.divInt += ' title="'+this.altName+'"' else if( this.altName != null ) this.divInt += ' title=""' this.divInt += '><img name="'+this.name+'Img" src="'+this.imgOffSrc if( this.altName ) this.divInt += '" alt="'+this.altName else if( this.altName != null ) this.divInt += '" alt="' this.divInt += '" width='+this.w+' height='+this.h+' border=0' if( !is.ns4 ) this.divInt += ' style="cursor:pointer"' this.divInt += '></a>' } Code: button41 = new ObjButton('button41',null,679,0,53,32,1,54,'div') button41.setImages('images/0807_help.jpg','images/0807_help_over.jpg','images/0807_help_over.jpg') button41.onUp = button41onUp button41.hasOnUp = true button41.capture=4 button41.setAccessKey(2) button41.setTabIndex(2) button41.build() 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 im no jQuery rookie but for the first time ...instead of simply writing out the animation jQuery('element').hide() in that way.... i instead needed to keep track of the functions so i wrote it like function hidetheElement() { jQuery('element').hide() } but now i need to run 2 of those functions together after a click ...for example jQuery('ClickedElement').click( movethelement,hidethelement ) see what i mean?....i dont know how to properly run two defined functions whats the proper syntax.... and here is my actual code for reference (its basically a menu link being clicked...hiding one page...and showing another....i needed to define the functions so if a menu link is clicked it could hide every other page first...by function....and then call a function to show the page Code: jQuery(document).ready( function() { jQuery('#ladiesmenu').click( previewoff,ladieson ); function previewoff() { jQuery('#preview').fadeOut(500); } function ladieson() { jQuery('#ladies').fadeIn(500); } I need to input the functions for the buttons ( Push, Pop,Peek, Enqueue, and Dequeue) nothing I try works. Can anyone possible help me with one of the push, pop or peek, and then one of the Enqueue or Dequeue (any information I see online always has to do with wordpress which im not using) . Im really not asking for someone to do all the work for me, I just need a start. ok here is my code with the buttons just no functions <html> <head> <title>COP2500 - Lab 9</title> </style></head> <body> <center> <h3><b>COP2500 Assignment 9</b></h3> <b>Queue:</b> <form name="queue"> <input type=text size=60 name="display"><br> <input type=text size=5 name="entry"> <input type=button value="Enqueue" onClick="enqueue()"> <input type=button value="Dequeue" onClick="dequeue()"> </form> <hr> <b>Stack:</b> <form name="stack"> <table> <tr> <td>Entry: <input type=text size=5 name="entry"><br> <input type=button value="Push" onClick="push()"><br> <input type=button value="Pop" onClick="pop()"> <br> <input type=button value="Peek" onClick="peek()"><br> </td> <td><textarea name=display rows=20></textarea></td> </tr> </table> </form> </center> <script language="JavaScript"> var myqueue = new Array(); var front; var back; front = 0; back = -1; var mystack = new Array(); var top; top = -1; function enqueue() { // This function should take the value from the 'entry' text box and // add it to the back of the queue. The 'back' queue variable must be // incremented. // Since the queue changed, call the display function. Done. display_queue(); } function dequeue() { // This function should display the value of the 'front' element // in the queue using the 'alert' function and then increment the value // of the front variable. // if the queue is empty, i need to say so. // Since the queue changed, call the display function. Done. display_queue(); } function push() { // This function should add the value in the 'entry' text box to the stack, // and then increment the value of the 'top' variable. // Since the stack changed, call the display function. . display_stack(); } function pop() { // This function should use the alert function to display the top // of the stack and then remove the top item from the stack. // You can 'remove' the item simply by decrementing the value of 'top'. // If the stack is empty, it needs to say so. // Since the stack changed, call the display function. . display_stack(); } function peek() { // This function should use the 'alert' function to display the top // of the stack but not change the stack. If stack is empty,it needs to say so. } // ***************************************************************** // Do not edit anything below this line. Use the functions as given. // ***************************************************************** function display_queue() { var output; var i; output = " "; for (i = back; i >= front; i--) output = output + myqueue[i] + " "; document.queue.display.value = output; } function display_stack() { var output; var i; output=""; for (i = top; i > -1; i--) output = output + mystack[i] + "\n"; document.stack.display.value = output; } </script> </body> </html> . Why do we have functions without parentheses at times? Ex 1) http://www.youtube.com/watch?v=OHYFNDzlDTE (On 2:18) Ex 2) At the bottom: Code: var panel, flag; function mousemoveResponse(e) { var x, y; if( window.event ) { x= event.x; y=event.y; } else if(e) { x=e.pageX; y=e.pageY; } if(flag) { panel.innerHTML = "Mouse is at X: " + x + ", Y: " + y ; } } function mouseoverResponse() { flag = false; panel.innerHTML = "Mouse is Over"; } function mouseoutResponse() { flag = true ; } function init() { panel=document.getElementById("panel"); flag = true; panel.innerHTML="Move the mouse..." ; document.onmousemove=mousemoveResponse; panel.onmouseover=mouseoverResponse; panel.onmouseout=mouseoutResponse; } onload=init; Code: <html> <head> <script> //declare variable //var temp = 0; var Num = parseInt(prompt('Enter an Intger')); // starts the function factorial factorial(Num); //The function is declared function factorial(currentNumber) { if(currentNumber > 1) { //temp = temp + (currentNumber); factorial(currentNumber - 1); alert(currentNumber); } else { alert("here"); } } </script> </head> <body> </body> </html> This code is suppose to take the prompt number and keep subtracting one if > 1 but it seems to be not doing that at all and doing the else statement first then + till it gets to the prompt number. I have been staring at it for a while now and cant work it out. Thanks Hi, I am creating a mashUp with google maps and have a function that creates the map, marker, infowindow and all works great. I want to add more functions to that functions file. Do I start with another function Name() put my function in the {} and then I am going to use the onclick event when I want the function to run. I also am going to add more functions to this file Is that the correct way to keep adding functions? And what is the best way of calling them in my html file? Answers and examples would be great thank you I'm a newbie student coder for now, hoping to enter the wonderful world of software engineering in another year. I put together a very simple site for a class and all is well, but my "Contact SRS" form doesn't seem to want to run my JavaScript code even though I've used a JS debugger which returned no errors. When I click the Submit button it's supposed to validate the form. But I keep getting "Error on page" in the bottom IE 7 message bar (where it usually says "Done" when you load a page). There is another function that also does not work - it's in the Telephone number fields - it' supposed to check that the values entered are numbers. Would anyone be kind enough to try to run this page in your browser and see if the validation functions runs for you? If they don't, could you offer any suggestions as to code errors or possible browser settings that might be causing the problem? Thanks in advance to anyone offering their time!!! Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <meta name="description" content="Page used to contact SRS" /> <meta name="keywords" content="resume, resumes, job, jobs, job market, job info, interview tips, job interview, salary, salaries, cover letter, cover letters, SRS, Superior Resume Source, business cards, help with resume, help with job search" /> <title>Contact SRS</title> <link rel="stylesheet" href="style.css" type="text/css" media="screen" /> <script type="text/javascript">/* <![CDATA[ *//* ]]> */ function checkForNumber() { if (isNan(document.forms[0].area.value)){alert("You must enter a numerical value");return false;} else if (isNan(document.forms[0].exchange.value)){alert("You must enter a numerical value");return false;} else if (isNan(document.forms[0].phone.value)){alert("You must enter a numerical value");return false;} } // function validateForm () // { // if(document.forms[0].firstname.value==""){alert("You must enter your first name.");return false;}} // } // else if(document.forms[0].lastname.value== ""){alert("You must enter your last name.");return false;} // else if(document.forms[0].address1.value== ""){alert("You must enter your address.");return false;} // else if(document.forms[0].city.value== ""){alert("You must enter a city.");return false;} // else if(document.forms[0].state.value== ""){alert("You must enter a state.");return false;} // else if(document.forms[0].zip.value== ""){alert("You must enter your zip code.");return false;} // else if(document.forms[0].area.value== ""||document.forms[0].exchange.value== ""||document.forms[0].phone.value== "") // {alert("You must enter a complete phone number.");return false;}} // else {alert('Thank you! SRS will contact you within one business day.');}} function isEmpty(strfirst, strlast, straddress, strcity, strstate, varzip) { strfirst = document.forms[0].firstname.value strlast = document.forms[0].lastname.value straddress = document.forms[0].address1.value strcity = document.forms[0].city.value strstate = document.forms[0].state.value varzip = document.forms[0].zip.value //name field if (strfirst == "" || strlast == null || strfirst.charAt(0) == ' ') { alert("\"First Name\" is a mandatory field.\nPlease amend and retry.") return false; } //last name field if (strlast == "" || strlast == null || strlast.charAt(0) == ' ') { alert("\"Last Name\" is a mandatory field.\nPlease amend and retry.") return false; } //address field if (straddress == "" || straddress == null || straddress.charAt(0) == ' ') { alert("\"Address\" is a mandatory field.\nPlease amend and retry.") return false; } return true; } //city field if (strcity == "" || strcity == null || strcity.charAt(0) == ' ') { alert("\"City\" is a mandatory field.\nPlease amend and retry.") return false; } //state field if (strstate == "" || strstate == null || strstate.charAt(0) == ' ') { alert("\"State\" is a mandatory field.\nPlease amend and retry.") return false; } } function check(form)){ if (isEmpty(form.firstname)){ if (isEmpty(form.lastname)){ if (isEmpty(form.address1)){ if (isEmpty(form.city)){ if (isEmpty(form.state)){ } } } } } return false; } </script> </style> </head> <body> <a name="top"></a> <div id="container"> <div id="header"> <h1></h1> </div> <div id="content"> <h2>Contact SRS</h2> <p>Use this page to contact SRS and/or order products and services. Refer to our <a href="services.htm">Services</a> page for pricing.</p> <p><strong>Remember, our work is guaranteed or your money back!</strong></p> </div> <div id="sidebar"> <ul> <li><a href="index.htm">Home</a></li> <li><a href="about.htm">About SRS</a></li> <li><a href="services.htm">Services</a></li> <li><a href="contact.htm">Contact SRS</a></li> </ul> <div class="widget"> Did you know that employers prefer CV's that are limited to three pages or less? </div> <div class="widget"> First impressions last a lifetime... write a Thank You letter EVERY time! </div> <div class="widget"> Want to know your personality type? Take this FREE <a href="http://www.careerfulfillment.com/?hop=daviduk"> personality test.</a> </div> </div> </div> <form method="get" enctype="application/x-www-form-urlencoded"> <table border="0"> <tr> <td id="contact table" valign="top"> <h3><strong>Contact SRS</strong></h3> <p><strong>* Required</strong><p> <p>First Name*<br /> <input type="text" name="firstname" size="50" /> </p> <p>Last Name*<br /> <input type="text" name="laststname" size="50" /> </p> <p>Address*<br /> <input type="text" name="address1" size="50" /><br /> <input type="text" name="address2" size="50" /> </p> <p>City, State, Zip*<br /> <input type="text" name="city" size="34" /> <input type="text" name="state" size="2" maxlength="2" /> <input type="text" name="zip" size="10" maxlength="10" onchange="return checkForNumber;" /> </p> <p>Telephone*</p> <p>(<input type="text" name="area" size="3" maxlength="3" onchange="return checkForNumber;" />) <input type="text" name="exchange" size="3" maxlength="3" onchange="return checkForNumber;" /> <input type="text" name="phone" size="4" maxlength="4" onchange="return checkForNumber;" /></p> <strong>Check the reason(s) for your inquiry?*</strong> <p><input type="checkbox" name="geninquiry" value="General_Inquiry" />General Inquiry <br/> <input type="checkbox" name="help" value="Help" />Help<br/> <input type="checkbox" name="new_resume" value="Order New Resume" />Order a New Resume <br /> <input type="checkbox" name="Update_resume" value="Update My Resume" />Update My Resume <br/> <input type="checkbox" name="cover_letter" value="Order Cover Letter" />Order a Cover Letter <br /></p> <textarea rows="10" cols="50">Type your comments here</textarea> <p><input type="button" name="Submit" value="Submit" onsubmit="return check(this);" /> <input type="reset" /></p> </td> </tr> </table> </form> <a href="#top">Back to Top</a><br /> </body> </html> I would really like to thank the guys that have been helping me. I think my brain would have exploded otherwize. Some of the problems have been simple misspellings, but when you have been staring at the same thing for hours it can sorta slip by. HOPEFULLY this will be the last thing that I need some help with. Bascially Im not sure if Im using the function command properly. When Submit Details is click it should validate the form and then when Calculate is pressed calculate the form (obviously). I think maybe my var Array table is wrong? And the way the functions are set out doesnt seem it sit right. Code: <script type="text/javascript"> var element; var itemArray = new Array(); itemArray [0] = "Bike" //not sure if these are properly writen?// itemArray [1] = "TV" itemArray [2] = "iPod" itemArray [3] = "Car" var flag="OK"; var count = 0 document.write ("<form name='myform'><br><table>"); while (count <= 3) { if (count < 3) { document.write ("<tr><td><value>Enter money from " + itemArray [count] + " sale.</td><td><input type='text' name=" + itemArray [count] + "></td></tr>"); count++ } else { document.write ("<tr><td><value>Enter the price of " + itemArray [count] + ".</td><td><input type='text' name=" + itemArray [count] + "></td></tr>"); document.write ("<tr><td><input type='submit' value='Submit Details' onClick='validateform'</td></tr>"); document.write ("<tr><td><input type='submit' value='Calculate Details' onClick='calculateform'</td></tr></table></form>"); count++ } } function validateform() //<=== doesnt run { element=document.getElementsByTagName ('input'); for (counter=0; counter<element.length; counter++) { switch (element[counter].type) { case "submit": break; default: if (isNaN(element[counter].value) || (element[counter].value == "") ) { alert("You need to enter a number into " + element[counter].name); flag="NotOK" } else { Bike=element[0].value; TV=element[1].value; iPod=element[2].value; Car=element[3].value; } break; } } } function calculateform() //<=== Doesnt run either { if (flag=="OK") { if ( (Number(element[Bike])) && (Number(element[TV])) && (Number(element[iPod])) && (Number(element[Car])) ) //<========= Gets Bike is not defined error easy// { TotalMoney= parseFloat (Bike) + parseFloat (TV) + parseFloat (iPod) if (TotalMoney >= Car) { alert ("The total money is " + TotalMoney + " and the car price is " + Car + " and you can afford the car") } else { alert ("The total money is " + TotalMoney + " and the car price is " + Car + " and you cannot afford the car") } } } } </script> Hi, 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 right at the beginning of learning javascript and having trouble with my first project Code: <html> <head> </head> <body> <form onsumbit="return add_hq()"> Headquarters: <select name="ork_hq_list" id="ork_hq_list" > <option value="warboss.html">Warboss<br /> <option value="big_mek.html">Big Mek<br /> <option value="weirdboy.html">Weirdboy<br /> </select> <input type="submit" value="Add"/> </form> <script type="text/javascript"> function add_hq() { hq = document.getElementById("ork_hq_list"); window.open("hq.options[hq.selectedIndex].value","Warboss","width=700"); return false; }; </script> </body> </html> Basically I have a 3 element drop-down form that is supposed to pop up a small window depending on what choice is selected when the submit button is pressed, but the selection is not getting to the code somehow. Can anyone see what I've done wrong? Hello all, I’ve got a homework to do and I'm stuck, as you can see i have done all the function's (i think they are ok but not shure) with a main program I'm stuck don’t know even where to begin :/ could anyone please please help a bit? best regards <HTML> <HEAD> <TITLE> The game of 21 </TITLE> <SCRIPT LANGUAGE = "JavaScript"> //FUNCTIONS /* *removes a given number of sticks * *function takes one argument numberToRemove that represents the number of sticks to be removed * if numberToRemove is more than numberOfSticks, reduces numberOfSticks to 0 * otherwise reduces numberOfSticks by numberToRemove *function returns no value */ function removeSticks(numberToRemove) { if (numberOfSticks< numberToRemove) { numberOfSticks =0 } else { (numberOfSticks = numberOfSticks - numberToRemove); } } /* *switches current player * *function takes no argument * if current player is 1, sets current player to 2 * otherwise sets current player to 1 *function returns no value */ function switchCurrentPlayer() { if (currentPlayer ==1) { return currentPlayer = 2; } { return currentPlayer = 1; } } /* *gets a number from a prompt dialogue * *function takes no argument * prompts the current player for a number of sticks to remove, with a suitable message *function returns the number the player enters */ function getChosenNumber() { ChosenNumber = window.prompt('Player ' + currentPlayer + ': Please enter either 1, 2 OR 3.'); return ChosenNumber; } //VARIABLES -- do not change this section var numberOfSticks = 21;//number of matchsticks, initially 21 var currentPlayer = 1;//player whose turn it is, Player 1 goes first var numberChosen;//variable used to hold the number the current player chooses //MAIN PROGRAM The players take turns to choose how many matches to remove, as long as there are still matches left. After each go the program outputs the number of matches that still remain and if this number is zero a message is displayed to say the current player is the winner. The turn then passes to the other player. </SCRIPT> </HEAD> <BODY> </BODY> </HTML> I would like to start off by saying I know there isn't a sure fire, 100% way to tell if javascript is enabled on a users browser. Because of this, it's a good idea to check form input using a php (or another server-side language) function. Now, let's say the user DOES have javascript enabled. I would like to check that same form input with a javascript function, instead of a php function. How would I be able to do that? If both php and javascript functions are in the same script, how does the browser know which one to run and how can I make it run the javascript function if the user has javascript enabled? |