JavaScript - Form Functions
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? Similar TutorialsHi guys, I need some help here.. I have created a simple JS and HTML NAME form validation and checked box as shown (If anyone can help me about the check box a better and easy way to code would be great). I would like to use the functions that I have created - can anyone tell me HOW I can use them please? I tried to use like this.. Code: var name = document.getElementById('name').value; if(name(!notEmpty && !isAlphabet)) { error_mesg += "\nPlease enter your Name"; error_num++; } ..but it does not work...anyone can give me some idea? Code: .. .. <script type='text/javascript'> function formValidation(){ var error_mesg = "Following error found\n"; var error_num = 0; var name = document.getElementById('name').value; if(name==""){ error_mesg += "\nPlease enter your Name"; error_num++; } var terms = !document.getElementById('terms').checked; //Can anyone tell me what is the function of "checked" here for? if (terms){ error_mesg += "\nPlease check the terms and conditions"; error_num++; } if(error_num>0){ alert(error_mesg); elem.focus(); return false; }else{ //submit form return true; } } function notEmpty(elem, error_mesg){ if(elem.value.length == 0){ alert(error_mesg); elem.focus(); // set the focus to this input return false; } return true; } function isAlphabet(elem, error_mesg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(error_mesg); elem.focus(); return false; } } .. .. [HTML FORM] .. <form name="form" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onsubmit="return formValidation()"> <tr align="left" valign="top> <td width="20%">NAME:<font color="#CE0000" >*</font></td> <td width="80%"><input name="name" type="text" id="name" size="30" /></td> </tr> <tr><td><input type=checkbox name=terms value='yes'>I agree to terms and conditions </td></tr> .. .. <input type="hidden" name="action" value="register"/> <input name="submit" type="submit" value="Proceed" /> I have been working on a JavaScript form with validation and I cant get it to work right. The form is supposed to validate the name, E-mail, Phone number, Password and confirmation, Drop-down selection, Question reply, yes and no radios, and 3 preferences check-boxes. It is also supposed to verify that the passwords match, not allow any letters or special characters in the phone number box, and remove the default text when a user clicks on the Name, E-mail, and Question reply boxes. I've been checking over the code for almost a month now and I can't figure out why it is not working. This is my entire code. [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/html; charset=utf-8" /> <title>Contact</title> <script type="text/javascript"> /* <![CDATA[ */ function onlyDigits(objtextbox) { var exp = /[^\d]/g; objtextbox.value = objtextbox.value.replace(exp,""); } function textdisappear(txt) { if (txt.value == txt.defaultValue) { txt.value = "" } function passmatch() { if (document.forms[0].psswrd2.value != document.forms[0].psswrd1.value) { window.alert("You did not enter the same password!"); document.forms[0].psswrd1.focus(); } function validate() { var name = document.form1.Name; var email = document.form1.Email; var phone = document.form1.Telephone; var question = document.form1.selection; var reply = document.form1.questionreply var word1 = document.form1.psswrd1 var word2 = document.form1.psswrd2 var chkradio = false; var chkbox = false; if (name.value == "") { window.alert("Name please."); name.focus(); return false; } if (email.value == "") { window.alert("E-mail is blank."); email.focus(); return false; } if (email.value.indexOf("@", 0) < 0) { window.alert("Enter valid e-mail please."); email.focus(); return false; } if (email.value.indexOf(".", 0) < 0) { window.alert("Enter valid e-mail please."); email.focus(); return false; } if ((phone.value == "")) { window.alert("Telephone number please."); phone.focus(); return false; } if (word1.value == "") { window.alert("Password please."); word1.focus(); return false; } if (word2.value == "") { window.alert("Re-type password please."); word2.focus(); return false; } if (question.selectedIndex < 1) { alert("Choose question please."); question.focus(); return false; } if (reply.value == "" || reply.value == "Question reply") { window.alert("Question reply please."); reply.focus(); return false; } for (var i=0; i<2; ++i) { if (document.form1.confirmreply.checked == true) { chkradio = true; break; } if (chkradio != true) { window.alert("Yes or no please."); confirmrelpy.focus(); return false; } for (var i=0; i<3; ++i) { if (document.form1.hobby.checked == true) { chkbox = true; break; } if (chkbox != true) { window.alert("Choose preference."); hobby.focus(); return false; } return true; } /* ]]> */ </script> </head> <body> <center><h1>Contact</h1></center> <form method="post" action="mailto:someemail@somedomain.com" name="form1" onsubmit="return validate();"> <h3>Your Details</h3> <p>Name:* <input type="text" name="Name" value="Enter Name" onfocus="textdisappear(this)" ></p> <p>E-mail:* <input type="text" name="Email" value="Enter E-mail" onfocus="textdisappear(this)" ></p> <p>Phone Number:* <input type="text" name="Telephone" onkeyup="onlyDigits(this)"><br> <br /> <h3>Password and Secret Question</h3> Password:<br /> <input type="password" name="psswrd1" value="" />*<br /> Confirm:<br /> <input type="password" name="psswrd2" value="" onblur="passmatch()" />*<br /> <p>Choose a question:*<br /> <select type="text" value="" name="selection"> <option> </option> <option>Where was your elementary school?</option> <option>Who was the first person you ever kissed?</option> <option>What was your first car?</option> <option>Who is your favorite author?</option> </select><br /> reply<br /> <input type="text" name="questionreply" value="Question reply" onfocus="textdisappear(this)" />*<br /> <h3>Offers</h3> Do you want any special offers sent to you?*<br /> Yes<input type="radio" name="confirmreply" value="Yes"/>No<input type="radio" name="confirmreply" value="No" /> <h3>Which preference do you have?*</h3> <input type="checkbox" name="hobby" value="check"/>Inside Activities<br /> <input type="checkbox" name="hobby" value="check"/>Outside Activities<br /> <input type="checkbox" name="hobby" value="check"/>Both<br /> <br /> <p><input type="submit" value="Submit" name="submit" /> <input type="reset" value="Reset" name="reset"></p> </form> </body> </html> [CODE] use in form fields - onBlur="chkalpha(this)" function chknum(field) { var valid = "0123456789"; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only numeric data is accepted!"); field.value=""; field.focus(); field.select(); } } function chkalpha(field) { var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only alphabetic data is accepted!"); field.value=""; field.focus(); field.select(); } } function chkalphanum(field) { var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_-. "; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only alphanumeric data is accepted!"); field.value=""; field.focus(); field.select(); } } when user clicks submit first it should check to see if a name from the dropdown has been selected then it should check to make sure all radio buttons were selected. code to check if a name was selected in the drop down. Code: <script type="text/javascript"> window.onload=function(){ document.forms[0].onsubmit=function(){ return formValid(this); } } function formValid(formObj){ var sel=formObj.getElementsByTagName('select'); var len=sel.length; var msg = "You forgot to select your name" var flg=false; for(var i=0;i<len;i++){ if(sel[i].selectedIndex==0){ msg; flg=true; } } if(flg){ alert(msg); return false; }else{ return true; } } </script> <br><br> <html> code that checks to see if all radio buttons were selected. Code: function validateTest() { var focus_me = null; var msg = ""; var form = document.forms[0]; for ( var game = 1; game <= 999999; ++game ) { var rbg = form["game" + game]; if ( rbg == null ) break; // no more games if ( ! rbg[0].checked && ! rbg[1].checked ) { msg += rbg[0].value + " vs. " + rbg[1].value + "\n"; focus_me = focus_me || rbg[0]; } } if (msg != "") { var prefix = "\n WARNING: The following Games(s) were not selected:\n\n"; var suffix = "\nClick OK and select all games before clicking submit.\n\n"; alert(prefix + msg + suffix); if (focus_me) focus_me.focus(); return false; } else{ return true; } } Code: center> <INPUT TYPE=SUBMIT VALUE="submit" onClick="Validate(this.form, 'game1')"> </FORM> how can i add these two functions together so it validates both? <?php session_start(); include_once "../c-library/errorcheck.inc.php"; function viewForm($input,$errors){ //$array[] = $var; $num_days= array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21 ","22","23","24","25","26","27","28","29","30","31"); $num_months = array(1=>"Jan",2=>"Feb",3=>"Mar",4=>"Apr",5=>"May",6=>"Jun", 7=>"Jul",8=>"Aug",9=>"Sept",10=>"Oct",11=>"Nov",12=>"Dec" ); $gender = array("Male","Female"); ?> <!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>Register</title> <script src="reload_vals.js" type="text/javascript"></script> <style media="all"> table{ table-layout:auto; width:auto;} th{ text-align:right;} td #err{ color:#FF0000; font-weight:bold;} </style> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" > <h3><font face="Georgia" color="#000066" size="+2">Registeration</font></h3> <?php if (count($errors) > 0): echo "<p style='color:#ff0000'>*The following errors ocurred:</p>"; endif; ?> <table width="" border="1"> <tr> <th scope="row">Firstname:</th> <td><input name="fname" type="text" id="fname" size="28" value="<?php echo htmlentities($input['fname'])?>" /></td> <td id="err"><?php echo $errors['fname'] ?></td> </tr> <tr> <th scope="row">Lastname:</th> <td><input name="lname" type="text" id="lname" size="28" value="<?php echo htmlentities($input['lname'])?>" /></td> <td><?php echo $errors['lname'] ?></td> </tr> <tr> <th scope="row">Date of Birth:</th> <td> <select name="days" size="1" id ="days" > <option value='-------'>--Day--</option> <?php /* day starts here*/ (array)$num_days; foreach ($num_days as $day): printf("<option value=\"%s\" %s>%s</option>",$day,($days==$day ? "selected='selected'" : ""), $day); endforeach; /* day ends and months start here*/ ?> </select> <select name="" size="1" id =""> <?php /* month ends and starts here*/ ?> </select><select name="" size="1" id =""> <?php ?> </select> <br /><small style="text-align:center; color:#006600;">dd-mm-yyy</small> </td> <td><?php echo $errors['date'] ?></td> </tr> <tr> <th scope="row">Sex:</th> <td> <select name="" size="1" id =""> <?php /* Sex selection starts here;*/ /* Sex selection starts here; */ ?> </select></td> <td><?php echo $errors['sex'] ?></td> </tr> <tr> <th scope="row">Email:</th> <td><input name="email" type="text" id="email" size="28" value="<?php echo htmlentities($input['email']) ?>"/></td> <td><?php echo $errors['email'] ?></td> </tr> <tr> <th scope="row">Password:</th> <td><input name="password" type="password" id="password" size="28" value="<?php echo htmlentities($input['password']) ?>"/></td> <td><?php echo $errors['password'] ?></td> </tr> <tr> <th scope="row">Comfirm Password:</th> <td><input name="password2" type="password" id="password2" size="28" value="<?php echo htmlentities($input['password2']) ?>"/></td> <td> </td> </tr> <tr> <th scope="row"> </th> <td> </td> <td> </td> </tr> <tr> <th scope="row">I agree:</th> <td><input name="agree" type="checkbox" id="agree" value="<?php echo $input['agree']='agree'?>" /></td> <td><?php echo $errors['agree'] ?></td> </tr> <tr> <th scope="row"><input name="action" type="hidden" id="submitted" value="TRUE" /></th> <td><input name="add_newuser" type="submit" id="submit" value="I accept, Register me" /></td> <td> </td> </tr> </table> </form> </body> </html> <?php } function register_user($input){ include "../c-library/database.inc.php"; // $input = $_REQUEST; $input['fname'] = mysql_escape_string(stripslashes($input['fname'])); $input['lname'] = mysql_real_escape_string(stripslashes($input['lname'])); //$input['day'] $input['date'] = $input['year'].''.$input['month'].''.$input['day']; $input['sex'] = $input['sex']; $input['email'] = mysql_real_escape_string($input['email']); $input['password'] = mysql_real_escape_string(md5($input['password'])); $input['uid'] = uniqid(rand(16,32),true); $qr ="insert into users(id,Firstname,Lastname,Date_of_Birth,Sex,Email,Password,Userid) values('null','$input[fname]','$input[lname]','$input[date]','$input[sex]','$input[email]','$input[password]','$input[uid]')"; $results = mysql_query($qr,$sdayb); return $results; mysql_close($sdayb); echo "thanks";//header("Location: thankyou.html"); } /*ex. user enters - 19/11/1980 $var = explode('/', '19/11/1980'); $sdayd = $var[0]; $mm = $var[1]; $yyyy = $var[2]; */ if(isset($_POST['add_newuser'])): $inputs = $_POST; $setErrors = array(); if(!check_formerr($inputs, $setErrors)): viewForm($inputs, $setErrors); else: register_user($inputs); endif; else: viewForm(null, null); endif; ?> I am trying to do a custom add to cart to use with paypal and need to utilize javascript to achieve inserting some code or a weight value per the paypal forms' options choice. Here is my dilemma, All of my items have multiple weights, for instance the below example called Aqua Max 100 comes in .5lbs, 1.5lbs., 10lbs., 20lbs., and 50lbs. Paypal allows you to enter weight but it's one weight per item and I would have to create 5 Paypal buttons just for this one item to calculate the different weights per zip code. I need help making javascript insert the following code within the paypal forms' code upon option select before clicking submit? <input type="hidden" name="weight" value=".5"> <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="1.5"> <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="10 <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="20 <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="50 <input type="hidden" name="weight_unit" value="lbs"> The code I came up with is wrong as I'm getting an error but I was originally trying to make it enter a weight using a hidden fillable number and without any real javascript training, just alot of googling but I think I'm pretty close. Please take a look at the code I've came up with so far and maybe point me in the correct direction: <html> <body> <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="business" value="test@test.com"> <input type="hidden" name="currency_code" value="USD"> <input type='hidden'text' name='amt' id='amt' value="0.00"/> <table> <tr> <td> <input type="text" name="on0" value="Aqua Max 100">Aqua Max 100</td></tr> <tr><td> <select name="os0" onChange="getamt()"> <option value="select">Please Select</option> <option value="1/2 lb.">1/2 lb. $3.99 USD</option> <option value="1 - 1/2 lbs">1 - 1/2 lbs $7.59 USD</option> <option value="10 lbs.">10 lbs. $25.80 USD</option> <option value="20 lbs.">20 lbs. $42.75 USD</option> <option value="50 lbs.">50 lbs. $86.20 USD</option> </select></td></tr> </table> <script type="text/javascript"> function getamt() { var sh=0; var choice = document.getElementById("os0").selectedIndex; if (choice == 0) { sh=0; } if (choice == 1) { sh=.5; } if (choice == 2) { sh=1.5; } if (choice == 3) { sh=10; } if (choice == 4) { sh=20 } if (choice == 5) { sh=50.00; } document.getElementById("on0").value=sh; } </script> <input type="image" src="https://images.paypal.com/images/sc-but-03.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> </body> </html> Ill tell you the story and then simplify it ok i have a computer site that you can build your own computer and whatnot but i just recently thought about how not everyone knows which parts are needed in a computer... my first design of the site had the name of the part in the select box as default but now i removed the name of each part outside of the select boxes but the problem now is i need some type of onLoad event to happen when the page loads to call out the functions that are associated with the selected boxes...... i have 2 fuctions in an external js file Code: function swapImage(sel,id){ document.getElementById(id).src = sel.value.split('#')[1]; } and Code: function Calculate(){ var a = parseFloat(document.comp.caseselect.value.split('#')[0]); var b = parseFloat(document.comp.powersupply.value.split('#')[0]); var sum = a+b; document.getElementById("total").innerHTML = '$'+sum; } when someone selects an item it adds the price to the price of other selected items and shows the total price elsewhere on the page... also shows a picture of the selected item on the page.. im just going to show the first select box to show you how all my select boxes are written Code: <p align="left">CASE</p> <center> <select name="caseselect" style="width:625px" onchange="Calculate(); swapImage(this,'caseimg');"> <option value="50#COOLER MASTER Elite 310red.jpg" selected="1">COOLER MASTER Elite 310 Red ($50.00)</option> <option value="50#COOLER MASTER Elite 310blue.jpg">COOLER MASTER Elite 310 Blue ($50.00)</option> <option value="50#COOLER MASTER Elite 310orange.jpg">COOLER MASTER Elite 310 Orange ($50.00)</option> <option value="50#COOLER MASTER Elite 310silver.jpg">COOLER MASTER Elite 310 Silver ($50.00)</option> </select> *not that it matters but yes there is an ending center in my html but its at the end of the group the image is sent here Code: <img src="start.jpg" id="caseimg" /> and the price is sent here Code: <span style="color:black; font-size:20pt">YOUR PRICE UPDATE</span><br /> <span id="total" style="color:white; font-size:32pt">$0 Nothing Selected</span> code works perfectly fine ONCE YOU SELECT SOMETHING ELSE but i need it to work when the page loads 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 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> 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 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; 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 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 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 Trying Make A Simple Program To Flip A Coin (Using Math.random). Every-time I Open My Browser Running The Code, The Button, Appears, But When Clicked, Nothing Happens... :confused: Can't Figure Out Why, If Someone Could Help Me Fix This, And Tell Me What I've Done Wrong, That Would Be Great, Thanks... Code: Code: <DOCTYPE html> <html> <head> </head> <body> <button type="button" onclick="myFunction()">Start</button><br> <script> function myFunction(){ for( i = 0; i < 20; i++){ if(Math.random() > 0.5){ document.write(\n + 'Heads')} else{ document.write(\n + 'Tails')}}} </script> </body> </html> |