JavaScript - Age Validation- Cant Find Error In My Code
hello
i have a form which when the user hits "submit," the info in the textboxes is entered to a database. the only textbox which is not entered to the DB is an "age" textbox, which i need to verify to see if user is 18yrs or older. if user is not 18 years or older, they get an alert telling them they arent 18+. if they are, then the form submits this is my code so far, and i dont get any alerts when i enter an age younger than 18: Code: <head> <script language="text/javascript"> var age; document.getElementById("userage").value = age; if (age >=18) document.location="feedbacksaveanddisplay.php"; else { alert('Sorry, we can not let you in!') document.location="content.html"; } </script> </head> <form method = "post" action = "FeedbackSaveAndDisplay.php"> <input type = "hidden" name = "user" value = "test"/> <input type = "hidden" name = "pwd" value = "test"/> <p>Enter your name, feedback, score</p> <table> <tr> <td>Name</td> <td> <input type = "text" name = "name" style="width:150px; height:20px;" /> </td> </tr> <tr> <td>Feedback</td> <td> <input type = "text" name = "feedback" style="width:150px; height:20px;" /> </td> </tr> <tr> <td>Score</td> <td> <input type = "text" name = "score" style="width:150px; height:20px;" /> </td> </tr> <tr> <td>Product</td> <td> <input type = "text" name = "product" style="width:150px; height:20px;" /> </td> </tr> <tr> <td>Age</td> <td> <input type = "text" name = "age" style="width:150px; height:20px;" /> </td> </tr> <tr> <td colspan = "2"> <input type = "submit" value = "Submit" /> </td> </tr> </table> </form> any tips/advice on how to fix my code? the problem i think is in the javascript... will greatly appreciate any help thanks!! Similar TutorialsI am trying to do a title case project and can't figure out where I went wrong. Any help would be appreciated. <!DOCTYPE html> <html lang="en"> <head> <title>Title Case</title> <meta charset="utf-8"> <script type="text/javascript"> function titleCase() { var word = document.forms[0].string.value.split(" "); var cword = ""; for (var i = 0; i < word.length; i++) { cword = cword + word[i].substr(0, 1).toUpperCase() + word[i].substr(1).toLowerCase() + ((i < word.length - 1) ? " " : ""); } return cword; } </script> </head> <body> <h1>Title Case</h1> <form action="" method="get"> <p><input type="text" name="string" /> <input type="button" value="Convert to Title Case" onclick="titleCase()" /></p> </form> </body> </html> Hello, can you tell me why this code gives me undefined error? You can see the code in action he open this link http://www.w3schools.com/cn/html/try...=tryhtml_basic and paste this code on the left side of the webpage, then press 'edit and click me' heres the full code: Code: <html><head><title>eink</title></head> <body onload="aaa()"> <script type="text/javascript"> function aaa() { var word2 = document.getElementById('word'), letters = word2.innerHTML.split(''), spanified; for (var k = 0, j = letters.length; k < j; k++) { spanified += '<span class="style101">' + letters[k] + '</span>'; } word2.innerHTML = spanified; } </script> <style type="text/css"> .style101 { background-color: #FF0000; } </style> <h1 id="word">HOUSE</h1> </body> </html> Here is a picture, of how it looks: This is the script itself - no error messages are generated. Code: <script language="javascript" type="text/javascript"> function getXMLHTTPRequest() { try { req = new XMLHTTPRequest(); } catch(err1) { try { req = new ActiveXObject("Msxm12.XMLHTTP"); } catch(err2) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(err3) { req = false; } } } return req; } var http = getXMLHTTPRequest(); function getCattle(animal_id){ var myurl = 'find_cattle.php'; var CattleValue=animal_id; var modurl= myurl+"?d="+CattleValue; **************the alert returns the correct value from my selection and after than nothing, I never get my alert from the response portion alert("Looking For "+modurl); ******* http.open("GET", modurl, true); http.onreadystatechange=useHttpResponse; http.send(null); } function useHttpResponse(){ ************It never gets to this response alert("Made It To Response"); if (http.readyState == 4) { if(http.status == 200) { var ListValue = http.responseXML.getElementsByTagName("animal_id")[0]; document.getElementsById('cattle_data').innerHTML = animal_id.childNodes[0].nodeValue; } } } </script> thank you Hello: Many apologies if this is not an appropriate question here... but I have googled my fingers raw and haven't been able to find a script to do what I am looking for. I have little experience with JavaScript. I have a VBA script (code at the end of this post) that returns the date corresponding to a given occurrence of a given weekday, e.g. Ask it for the 3rd Tuesday in October 2012 and it gives you 16-OCT-2012. It defaults to current year if you don't pass the Year argument. It's a pretty simple script, but I need to either finds something in JavaScript that does the same thing, or convert the VBA code to JavaScript. I can't help but think that many people have already written scripts that do this. Any chance someone can lead me in a productive direction here? Regards, Steve Jones (update - I noticed the code didn't retain its formatting, so I attached a text file) -begin VBA code- Public Function xdate(m As Integer, n As Integer, wd As Integer, Optional y As Integer = 0) As Date '// m = 1-12 (Jan-Dec), n = 1-5 (1st-4th, last), wd = 1-7 (Sun-Sat), y = 1900-9999 or left blank for current year Select Case y Case 0 ' // Default. Use the current year. y = year(Date) Case 1900 To 9999 ' // treat the value as an explicit year Case -100 To -1, 1 To 100 ' // treat the value as an offset to be applied to the current year y = year(Date) + y Case Else ' // invalid value. Insert whatever error processing you like. End Select Select Case n Case 1 To 4 '// first through fourth Case 5 '// last. We need to check to see it fell within the month specified, if not, use 4. xdate = DateSerial(y, m, (8 - weekday(DateSerial(y, m, 1), (wd + 1) Mod 8)) + ((n - 1) * 7)) If month(xdate) <> m Then n = 4 End If Case Else ' // invalid value - insert error processing code here if you like. ' // Probably should check the other arguments as well. End Select xdate = DateSerial(y, m, (8 - weekday(DateSerial(y, m, 1), (wd + 1) Mod 8)) + ((n - 1) * 7)) End Function -end vba code- I'm teaching myself how to build websites; up until now I have made websites using tables within tables and it's all fairly straight forward, now I realise that divs and css allow you to do soooo much more! I have put these files in a temp folder on my website so not to over write the current site. Basically I have followed this online tutorial (http://www.cryer.co.uk/resources/jav...show_links.htm) but when I test the slideshow, it doesn't work. the link is: www.telecaretechnology.com/telecare2/index.html Since I have started writing this, my css file seems to have had a wobbly - I assume my problem is where I'm trying to use server-side include?? Is that the best way to add these files? the javascript I have used to make the slideshow run is he http://www.telecaretechnology.com/te...2/slideshow.js I would really appreciate any advice! Kind Regards, Jamie I am trying to set up a looping structure that tests to see if the user enters a value. If the textbox is null then a global variable is false otherwise a checkbox is checked and the global variable is true. below is what i have done so far, please assist me. var isValid = false; window.onload = startForm; function startForm() { document.forms[0].firstName.focus(); document.forms[0].onsubmit = checkEntries; alert("You have been added to the list") } function checkEntries() { var menus = new Array(); var formObject = document.getElementsByTagName('*'); for (var i=0; i < formObject.length; i++){ if (formObject[i] == "myform") menus.push(formObject[i]); if (document.forms[0].firstName.value.length==0 || document.forms[0].firstName.value.length == null){ isValid= false; alert("Please enter a first name"); } else (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].lastName=="" || document.forms[0].lastName== null){ alert("Please enter a last name"); isValid = false; } else (document.forms[0].check1.checked=true); isValid=true; if (document.forms[0].email=="" || document.forms[0].email== null) { alert("Please enter a valid email"); } else return (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].bDate=="" || document.forms[0].bDate== null) { isValid=false; alert("please make sure you enter a valid birth date."); } else (document.forms[0].check0.checked=true); isValid=true; } } here is the form html... <form name="myform" > <input type="checkbox" name="check0" class="check0" id="check0" > First: <input type="text" name="firstName" id="firstName"> <BR> <input type="checkbox" name="check1" class="check1" id="check1" > Last: <input type="text" name="lastName" id="lastName" ><BR> <input type="checkbox" name="check2" class="check2" id="check2" > E-Mail: <input type="text" name="email" id="email"> <BR> <input type="checkbox" name="check3" class="check3" id="check3" > Birthday (mm/dd/yyyy): <input type="text" name="bDate" id="bDate"> <BR> <input type="submit" value="Join our mailing List" /> </form> i have following code for edit news Code: <%@ Language="VBScript" %> <% Option Explicit %> <html> <head><title>News Management System - Update News</title> <script type="text/javascript"> <!-- var dtCh= "/"; var minYear=1900; var maxYear=2100; var EDate = (Date()); var endDate = Date.parse(EDate); endDate = endDate - 86400000 function isInteger(s){ var i; for (i = 0; i < s.length; i++){ // Check that current character is number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; } function stripCharsInBag(s, bag){ var i; var returnString = ""; // Search through string's characters one by one. // If character is not in bag, append to returnString. for (i = 0; i < s.length; i++){ var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; } function daysInFebruary (year){ // February has 29 days in any year evenly divisible by four, // EXCEPT for centurial years which are not also divisible by 400. return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 ); } function DaysArray(n) { for (var i = 1; i <= n; i++) { this[i] = 31 if (i==4 || i==6 || i==9 || i==11) {this[i] = 30} if (i==2) {this[i] = 29} } return this } function isDate(dtStr){ var daysInMonth = DaysArray(12) var pos1=dtStr.indexOf(dtCh) var pos2=dtStr.indexOf(dtCh,pos1+1) var strMonth=dtStr.substring(0,pos1) var strDay=dtStr.substring(pos1+1,pos2) var strYear=dtStr.substring(pos2+1) strYr=strYear if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1) if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1) for (var i = 1; i <= 3; i++) { if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1) } month=parseInt(strMonth) day=parseInt(strDay) year=parseInt(strYr) if (pos1==-1 || pos2==-1){ return "The date format should be : mm/dd/yyyy"; } if (strMonth.length<1 || month<1 || month>12){ return "Please enter a valid month"; } if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){ return "Please enter a valid day"; } if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){ return "Please enter a valid 4 digit year between "+minYear+" and "+maxYear; } if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){ return "Please enter a valid date"; } return ''; } //--> </script> <script type="text/javascript"> function Submitme() { var _message=''; var _errorEarlier=false; if(document.frm.newstitle.value == "") { _errorEarlier = true; _message = 'Please enter news title'; } if(document.frm.newsbody.value == "") { if (_errorEarlier){_message += "\r\nPlease enter news detail";} else{_errorEarlier = true;_message = "Please enter news detail";} } if(document.frm.newsdate.value == "") { if (_errorEarlier){_message += "\r\nPlease todays or future date";} else{_errorEarlier = true;_message = "Please todays or future date";} } var dt=document.frm.newsdate var SDate = frm.newsdate.value; var FormDate = Date.parse(SDate); var dateError = isDate(dt.value); if (dateError != ''){ if (_errorEarlier){_message += "\r\n" + dateError;} else{_errorEarlier = true;_message = dateError;} } else if(FormDate < endDate ) { if (_errorEarlier){_message += "\r\nPlease ensure that the Entered Date is greater than or equal to the Todays Date.";} else{_errorEarlier = true;_message = "Please ensure that the Entered Date is greater than or equal to the Todays Date.";} } if (_errorEarlier) { alert(_message);return false; } else { document.frm.action="update_record.asp"; document.frm.submit(); } } </script> <script type="text/javascript"> <!-- function isAlpha(keyCode) { if(keyCode==16) isShift = True; var res = ((keyCode >= 65 && keyCode <= 90) || keyCode == 8 || keyCode == 32) if (!res) document.getElementById("lblAlpha").style.visibility = "visible"; else document.getElementById("lblAlpha").style.visibility = "hidden"; return res; } //--> </script> </head> <body> <% 'declare you variables Dim SQL, connection, recordset,newstitle,newsbody,newsdate Dim sConnString, ID 'receive the id of the record passed through querystring ID=request.querystring("ID") 'Declare the SQL statement that will query the database SQL="SELECT * FROM latestNews WHERE ID=" & ID 'Create an ADO connection and recordset object Set Connection = Server.CreateObject("ADODB.Connection") Set Recordset = Server.CreateObject("ADODB.Recordset") 'define the connection string, specify database 'driver and the location of database sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("news_data.mdb") 'Open the connection to our database Connection.Open(sConnString) 'Open the recordset object, execute the SQL statement 'and return the record with the id that was sent recordset.Open SQL,connection %> <div align='center'> <table width="370" border="0" cellspacing="0" cellpadding="0" align="center"> <tr align="left" valign="top"> <td> <div align="center"> <p> </p> <!-- start the html form --> <form method="post" action="update_record.asp" name="form"> <input type="hidden" name="id" value="<%= recordset("id")%>"> <table border="2" bordercolor="#CCCCFF" cellspacing="0" cellpadding="4"> <tr> <td> News Title</td> <td> <input id="txtAlpha" type="text" name="newstitle" value="<%= recordset("newstitle")%>" size="50" class="cssborder" onkeyup="keyUP(event.keyCode)" onkeydown="return isAlpha(event.keyCode);" onpaste="return false;" /> </td> <td> <span id="lblAlpha" style="color: Red; font-size: 10pt; font-family: Arial; visibility: hidden;"> * Only Alphabets</span> </td> </tr> <tr> <td valign="top"> News Text</td> <td> <textarea cols="50" rows="8" name="newsbody" class="cssborder"><%= recordset("newsbody")%></textarea></td> </tr> <tr> <td> News Date</td> <td> <input type="text" name="newsdate" value="<%= recordset("newsdate")%>" size="12" class="cssborder"><font color="#CC0000">(mm/dd/yyyy)</font></td> </tr> <tr> <td colspan="2"> <input type="hidden" name="id" value="<%=id%>"> <input type="hidden" name="ispostback" value="1"> <input type="submit" value="update" class="cssborder" onclick="return Submitme();" /> </table> <br> <br> </form> <!-- end the html form --> </div> </td> </tr> </table> </div> <% 'close the connection and recordset objects recordset.Close Set recordset=Nothing connection.Close Set connection=Nothing %> </body> </html> but when i leave blank all fields it cannot check them. and submit the form without displaying any error. wht wrong in this code?? I'm facing a validation error, whenever I leave any of the fields blank, it gives me a warning and then it redirects me to (index.php?option=com_ccnewsletter&view=ccnewsletter) What I wanna know is how can I freeze the page until all fields are filled? This is the javascript code: Code: <script type="text/javascript"> function formsubmit(task) { var form = document.subscribeFormModule; if(task == "addSubscriber") { if(form.name.value== "") { alert('<?php echo $parameters['namewarning']; ?>'); } else if(form.email.value == "") { alert('<?php echo $parameters['emailwarning']; ?>'); } else if(( form.email.value.search("@") == -1) || ( form.email.value.search("[.*]" ) == -1 )) { alert('<?php echo $parameters['emailwarning']; ?>'); } <?php if($parameters['showterm']) { ?> else if(form.terms_condition_ch.checked == false) { alert ('<?php echo $parameters['terms_cond_warn']; ?>'); } <?php } ?> else { form.task.value = "addSubscriber"; form.submit(); } } else if(task == "removeSubscriberByEmail") { if(form.email.value == "") { alert('<?php echo $parameters['emailwarning']; ?>'); } else if(( form.email.value.search("@") == -1) || ( form.email.value.search("[.*]" ) == -1 )) { alert('<?php echo $parameters['emailwarning']; ?>'); } else { form.task.value = "removeSubscriberByEmail"; form.submit(); } } } </script> And this is the form's code: Code: <div class="mainnewsletter"> <p><?php echo $parameters['introduction'] ?></p> <div class="module" style="padding-top: 0px;"> <div class="normalsublayout"> <form class="form-login" action="<?php echo JRoute::_('index.php?option=com_ccnewsletter&view=ccnewsletter');?>" method="post" name="subscribeFormModule" id="subscribeFormModule"> <p><div> <?php echo $parameters['name']; ?>: <div class="username-block"> <div class="input-field-l"> <input class="inputbox" type="text" onblur="if(this.value=='') this.value='YourName';" onfocus="if(this.value=='YourName') this.value='';" name="name" id="name" value="<?php echo $name; ?>" /> </div></div> </div> </p> <p> <div> <?php echo $parameters['email']; ?>: <div class="password-block"> <div class="input-field-l"> <input class="inputbox" type="text" onblur="if(this.value=='') this.value='youremail@domain.com';" onfocus="if(this.value=='youremail@domain.com') this.value='';" name="email" id="email" size="15" maxlength="35" value="<?php echo $email; ?>" /> </div> </div> </div> </p> <?php if($parameters['showterm']) { ?> <p> <input id="ccnewsletter" name="terms_condition_ch" class="inputbox" type="checkbox"> <a style="font-size:14px;color:#4E4E51; display: margin:0px 0px 0px 5px;text-decoration:none;" href='<?php echo $cid; ?>' class="modal" rel="{handler: 'iframe', size: {x: 700, y: 375}}"><?php echo $terms;?></a> </p> <?php } if($unsubscribe) { ?> <p> <input class="button" type="submit" id="addSubscriber" name="addSubscriber" value="<?php echo $parameters['subscribe']; ?>" onclick="formsubmit('addSubscriber');"/> </p> <p><input class="button" type="submit" id="removeSubscriberByEmail" name="removeSubscriberByEmail" value="<?php echo $parameters['unsubscribe']; ?>" onclick="formsubmit('removeSubscriberByEmail');"/> </p> <?php } else { ?><div class="readon-wrap1"> <div class="readon1-l"></div> <span class="readon-main"><span class="readon1-m"><span class="readon1-r"><input class="button" type="submit" id="addSubscriber" name="addSubscriber" value="<?php echo $parameters['subscribe']; ?>" onclick="formsubmit('addSubscriber');"/></span></span></span></div> <!--<p><center><input type="image" src="images/back_f2.png" id="addSubscriber" name="addSubscriber" value="<?php echo $parameters['subscribe']; ?>" onclick="formsubmit('addSubscriber');"/></center></p>--> <?php } ?> <input type="hidden" name="option" value="com_ccnewsletter" /> <!--<input type="hidden" name="task" value="addSubscriber" />--> <input type="hidden" name="task" value="" /> </form> </div> </div></div> I don't know, maybe I'm missing something because it was working fine a before. this is how i call the editor: Code: <!-- editor --> <? include "js/editor/buttons.php"; ?> <iframe id="textbox" class="Eddietor" src="js/editor/editor.php"></iframe><br /> <input type="hidden" id="content" name="content"> <!-- /editor --> and this is editor.js: Code: window.onload = function() { Editor = document.getElementById('textbox').contentWindow.document; Editor.designMode = "on"; document.forms[0].onsubmit = function() { var text = document.getElementById('text'); text.value = Editor.body.innerHTML; } } function doColor(colour) { document.getElementById("textbox").contentWindow.focus(); document.getElementById("textbox").contentWindow.document.execCommand("forecolor",false, colour); } function doClick(command) { document.getElementById("textbox").contentWindow.focus(); document.getElementById("textbox").contentWindow.document.execCommand(command, false, null); } function doLink() { var mylink = prompt("URL:", "http://"); if ((mylink != null) && (mylink != "")) { document.getElementById("textbox").contentWindow.focus(); document.getElementById('textbox').contentWindow.document.execCommand("CreateLink",false,mylink); } } function doImage() { myimg = prompt('URL:', 'http://'); document.getElementById("textbox").contentWindow.focus(); document.getElementById('textbox').contentWindow.document.execCommand("InsertImage", false, myimg); } another script i made is having problems with the ID="textbox" , it might be fixed if i change id and start using name="textbox" instead, but i don't know how to do this in js. need to edit the editor.js and change id="textbox"->to->name="textbox" can anyone help me? i got no idea how to use the getElementByName thingie , i'm trying to do this for 4 hours already and still no go. appreciated. Hi Folks, I'm new here, as well as to JavaScript, and am stuck. I'm trying to get something to validate using the W3C file validation, and I'm stuck. This is XHTML 1.0 Strick, and I know that isn't JS, but since the error involved JS I posted it here. If I would be better putting it in HTML please let me know. Everything works fine on the page, but I keep getting one single error. The > in Red is what shows up as the issue. Do ya'll see something glaringly obvious that I did wrong? Thanks for the help! Code: document.write("<a href='mailto:" + emLink + "' > "); Hi all. I am using the Inline Form Validation Engine jQuery plugin found here, and though I have posted at their forum as well, am having a heck of a time (not being well versed in js OR Ajax, unfortunately) All I need to do is edit the code so that when the onSubmit function is processed, it returns only the first error it encounters, rather than keeping and display the array of every error. I have picked through the code several times, and can't seem to find where the array is stored. I thought perhaps I could find a for loop to limit, but am at a complete loss. Is there anyone out there who can help? I can post the code if needed; I didn't want to post the entire file (since I don't know which snippet is the one I need!) Thank you in advance! Hello, Am new to this forum, as you can see this is my first post. Am having problem in validating my form, so i like you guys to help me out. Code: <html> <head> <title>Javascript form Validation</title> <script language="javascript"> <!-- function formValid() { var user = ducument.getElementById('userid'); var email = document.getElementById('emailid'); var select = document.getElementById('selection'); if(check_restrict(user,6,10)){ if(check_email(email,'Invalid Email address')){ if(check_select(select,'Please make a selection')){ return true; } } } return false; } function check_restrict(elem,min,max){ if(elem.value.length >= min && elem.value.length <= max){ return true; } else{ alert("Please enter " +min+ " to " +max+ "character") elem.focus(); return false; } } function check_email(elem,helperMsg){ var emailExp = /^[a-z0-9A-Z\.\-\_]+\@[a-zA-Z\-\.]+\.[a-zA-Z\.]{2,3}$/; if(elem.value.match(emailExp)){ return true; } else{ alert(helperMsg) elem.focus(); return false; } } function check_select(elem,helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg) elem.focus(); return false; } else{ return true; } } //--> </script> </head> <body> <form name="f1" onsubmit="return formValid()"> Username(6-10):<input type="text" id="userid" size=10 maxlength="15"><br/> Email Address:<input type="text" id="emailid" size=20 maxlength="20"><br/> <select id="selection"> <option>Please Choose</option> <option>Login</option> <option>Register</option> </select><br/> <input type="submit" value="Submit"> </form> </body> </html> Any help we be appreciated. Regards. You may not beable to help but I could not find any where else.. I am getting this error when i submit my form without the email address.. Attribute validation error for tag CFMAIL. The value of the attribute FROM is invalid. The length of the string, 0 character(s), must be greater than or equal to 1 character(s). The error occurred in \\NAWINFS02\home\users\web\b153\rh.chadwickorchids\name\name.cfm: line 2 1 : <cfmail 2 : from="#form.visitor_email#" 3 : to="orders@chadwickorchids.com;#form.visitor_email#" 4 : subject="Chadwick Orchids Name Your Own Orchid" How can I have this script go back to the form if it generates a error instead of going to the coldfussion error? please help I'd like to add validation for 5 digits (numbers only) to this code: if($("#newvalue1").val() == "" && operator == "Equals" || $("#newvalue2").val() == "" && operator == "Range" ){ good = false; alert("5 digits please."); I have tried the code below, but it's not working. Could anyone help, please? Thanks! if($("#newvalue1").val() == "" && operator == "Equals" || $("#newvalue2").val() == "" && operator == "Range" || $("#newvalue2").val() !/^\d{5} && operator == "Range" ){ good = false; alert("5 digits please."); I'm having trouble figuring out this code. I have a isInitialsTextValid function that checks to see if the user enters their initials in the correct format. Then I have a function checkInitials. In the checkInitials function I am supposed (1)to declare a variable to be used for the boolean value returned by the isInitialsTextValid function.(2)call the isInitialsTextValid function.(3)If the value returned is false, place focus back on initials textbox.(4)If the value return is true call the submit function. I'm not sure what I am doing wrong, but I get a checkInitials is no defined error from firefox and it is pointing to my xhtml file. Here is the relevant code. XHTML FILE 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> <title>Form Example</title> <script type = "text/javascript" src= "Lab17.js"> </script> </head> <body onload="giveInitFocus();"> <form name = "form1" action = ""> <p> <input type = "button" value = "Total Cost" onClick = "checkInitials();" /> <input type = "reset" value = "Reset Order Form" name = "reset" /> </p> <hr /> <p> Please Enter the Cashier's Initials. </p> <p> <label> Cashier's Initials: <input type = "text" name = "initials" id = "initials" /></label> </p> <p> JAVASCRIPT FILE Code: function isInitialsTextValid() { var init = document.form1.initials; var position = init.value.search(/^[A-Z]{2,3}$/); if(position !=0) { alert("Initials must be 2 or 3 capital letters" + "\n Please re-enter"); return false; } else return true; } function checkInitials() { var returned; isInitialsTextValid(); if(returned == false) { document.form1.initials.focus(); } else if(returned == true) { handleSubmitClick(); } } Hi, I have placed a form validation script in my HTML and I think its all in the right place, however, when i load the page an error appears saying can not get object. Once I click past it, the form validation works as normal. Not sure how to get rid of this error. I have placed the link to the external validation script in the document head Any ideas? HTML Code: <div class="mb_content"> <h2>Work</h2> <div class="mb_content_inner"> <p>IMAGES COMING SOON.</p> </div> </div> <div class="mb_content"> <h2>Contact</h2> <p class="con_details_tel">tel: </p> <p class="con_details_email">email: </p> <div class="mb_content_inner"> <form id='contactus' name='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'> <fieldset > <input type='hidden' name='submitted' id='submitted' value='1'/> <input type='hidden' name='<?php echo $formproc->GetFormIDInputName(); ?>' value='<?php echo $formproc->GetFormIDInputValue(); ?>'/> <input type='text' class='spmhidip' name='<?php echo $formproc->GetSpamTrapInputName(); ?>' /> <div><span class='error'><?php echo $formproc->GetErrorMessage(); ?></span></div> <div class='container'> <label for='name' >Name: </label><br/> <input type='text' name='name' id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/> <span id='contactus_name_errorloc' class='error'></span> </div> <div class='container'> <label for='email' >Email:</label><br/> <input type='text' name='email' id='email' value='<?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" /><br/> <span id='contactus_email_errorloc' class='error'></span> </div> <div class='container'> <label for='message' >Message:</label><br/> <span id='contactus_message_errorloc' class='error'></span> <textarea name='message' id='message'><?php echo $formproc->SafeDisplay('message') ?></textarea> </div> <div class='container'> <input type='submit' name='Submit' value='Submit' /> </div> </fieldset> </form> <script type='text/javascript'> var frmvalidator = new Validator('contactus'); frmvalidator.EnableOnPageErrorDisplay(); frmvalidator.EnableMsgsTogether(); frmvalidator.addValidation("name","req","Please provide your name"); frmvalidator.addValidation("email","req","Please provide your email address"); frmvalidator.addValidation("email","email","Please provide a valid email address"); frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)"); </script> </div> </div> </div> Here is the start of the javascript that is producing the error:- Code: function Validator(frmname) { this.validate_on_killfocus = false; this.formobj = document.forms[frmname]; if (!this.formobj) { alert("Error: couldnot get Form object " + frmname); return; } Can anyone help? Thanks nevblanc79 I'm trying to output something in a separate div if the information entered in the form is invalid. It is simply not working, no errors. Code: <script type="text/javascript" language="javascript"> function validateIGN(ign) { var validign = /^[a-zA-Z0-9]{1,30}$/; if (!validign.test(ign)) { document.getElementById.ignErrors.innerHTML = "<p>Your IGN is not formatted properly."; } else { } } </script> Heres the HTML where the onkeyup is.. Code: <form name= "newsletter" class="newsletter" action="doNewsletter.php" method="post"> <h2>Fill out this form if you want to be notified when the website is up!</h2><br/> <center><table class="twoslot"> <tr> <td>IGN(In Game Name):</td><td><input type="text" name="ign" onkeyup="return validateIGN(newsletter.ign.value);" /></td> </tr> <br/> <tr> <td>E-mail:</td><td><input type="text" name="email" /></td> </tr> <br/> <tr> <td> <center> <input type="submit" value="Submit" /> </center> </td> </tr> </table></center> <span style="font-size: .5em;">This is not working yet</span> </form> Hello! There is something wrong in the code below. What is it? Can you help me please? The form validation was working just fine when I added the last 'if' for zip code validation. The function didn't work and returned true. The code is: Code: <script type="text/javascript"> function validateForm() { var y=document.forms["form"]["firstname"].value; var f=document.forms["form"]["zipcode"].value; var x=document.forms["form"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (y==null || y=="NAME") { alert("First name must be filled out"); return false; } if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } } var re='/(^\d{5}$)/'; if (f!=re) { alert ("Not a valid address"); return false; } } </script> Any ideas or advice? Thank you in advance! hi, i need US zip code formatting on my page. as zip code can be 5 digits or 5-4 digits, our requirement is that when user types in 6th digit, hyphen automatically gets added between 5th and 6th digit. ex: user enters 100161,it should become formatted as 10016-1 and then user can continue to add rest of digits. pls advice, highly appreciate. thanks |