JavaScript - Javascript Client-side Validation Of A Form
Hi,
The following code is not working whose purpose is to validate the form with javascript. Please Help . Code: <html> <head> <script type='text/javascript'> function formValidator() { // Make quick references to our fields var firstname = document.getElementById('firstname'); var addr = document.getElementById('addr'); var zip = document.getElementById('zip'); var state = document.getElementById('state'); var username = document.getElementById('username'); var password = document.getElementById('passwd'); var email = document.getElementById('email'); var cpassword=document.getElementById('pass2'); var txtar=document.getElementById('ta'); var rad=document.getElementById('r1'); var cbox =document.getElementById('r1'); // Check each input in the order that it appears in the form! if(isAlphabet(firstname, "Please enter only letters for your name")) { if(isAlphanumeric(addr, "Numbers and Letters Only for Address")) { if(isNumeric(zip, "Please enter a valid zip code")) { if(madeSelection(state, "Please Choose a State")) { if(lengthRestriction(username, 6, 8)) { if(plengthRestriction(password,4,6)) { if(confpass(cpassword,"Please confirm")) { if(emailValidator(email, "Please enter a valid email address")) { if(istextareablank(txtar,"Please enter some text")) { if(isradiobuttselected(rad,"Please select any one radio buttons")) { if(ischeckboxselected(cbox,"Please select at least one checkbox")) { return true; } } } } } } } } } } } return false; } function notEmpty(elem, helperMsg){ if(elem.value.length === 0){ alert(helperMsg); elem.focus(); // set the focus to this input return false; } return true; } function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function lengthRestriction(elem, min, max) { var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter username between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } function plengthRestriction(elem, min,max) { var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter password between " +min+ " and " +max+ " characters"); elem.focus(); return false; } } function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function confpass(elem,helperMsg) { if ( confPasswd === "" ) { alert("Please fill in the Confirm Password"); document.forms[0].elements[7].focus( ); return false; } else if (document.forms[0].elements[6].value != document.forms[0].elements[7].value) { alert( "Your passwords do not match. Please retype and try again."); return false; } } function isEmpty(s) { return ((s === null) || (s.length === 0)); } function istextareablank(elem,helperMsg){ var i; <!-- Is empty? --> if (isEmpty(s)) return true; <!-- Search through string's' characters one by one until we find a non-whitespace character. --> for (i=0; i < s.length; i++) { <!-- Check that current character isn't' whitespace.--> var currchar = s.charAt(i); if (whitespace.indexOf(currchar) == -1) return false; } <!-- All characters are whitespace. --> return true; } function isradiobuttselected(elem,helperMsg){ <!-- Check to see if atleast one is checkbox checked or not--> for (j=10; j<=11; j++) { if(document.forms[0].elements[j].checked) { break; } else if (j>=11) { alert("Atleast Check on one of the radio buttons"); document.forms[0].elements[j].focus(); return (false); } } return(true); } function ischeckboxselected(elem,helperMsg) { for (j=12; j<=13; j++) { if(document.forms[0].elements[j].checked) { break; } else if (j>=13) { alert("Atleast Check on One of Our Services"); document.forms[0].elements[j].focus(); return (false); } } return(true); } </script> </head> <body> <form onsubmit='return formValidator()' > <br /> First Name: <input type='text' id='firstname' /><br /><br /> Address: <input type='text' id='addr' /><br /><br /> Zip Code: <input type='text' id='zip' /><br /><br /> State: <select id='state'> <option>Please Choose</option> <option>AL</option> <option>KE</option> <option>TX</option> <option>CH</option> </select><br /> Username(6-8 characters): <input type='text' id='username' /><br /><br /> Password(min 4 chars):<input type="password" id='passwd' /> <br/><br /> Confirm Password: <input id="pass2" Type="password" /><br/><br /> Email: <input type='text' id='email' /><br /><br /> Something about Yourself : <textarea name="1" cols="17" rows="4" id="ta"></textarea><br/><br /> Free Membership <input type="radio" id="r1"/> Paid Membership <input type="radio" id="r1"/><br/><br/> Friendship<input type="checkbox" id="box1" /> Networking <input type="checkbox" id="box1" /><br /><br /> <input type='submit' value='Submit' /> </form> </body> </html> Similar TutorialsI've literally tried everything. Read 26 tutorials, interchanged code, etc. My validation functions all work. My AJAX functions work (tested manually using servlet URL's). The second servlet validates the reCaptcha form that's generated on my webpage. After the form is validated, even if everything's correct, nothing happens upon clicking submit. I even have an alert pop up if with the captcha result, just for middle-layer debugging purposes. I want to do all of my validation clientside; none serverside. However, going to be tough if I can't get my god damn form to submit. I've been puzzled by this for close to 36 hours straight. I can't see, and I'm going to get some rest and hope that there is some useful insight on my problem when I return. html form: Code: <form id="f1" name="form1" onsubmit="validate_form(this); return false;" action="register" method="post"> <table cellspacing="5" style="border: 2px solid black;"> <tr> <td valign="top"> <table cellspacing="5"> <tr> <td>*First name</td> <td align="right"><span id="valid_one"></span></td> <td><input type="text" style="width: 320px;" id="fn" name="fn" onBlur="validate_one();"></td> </tr> <tr> <td align="left">*Last name</td> <td align="right"><span id="valid_two"></span></td> <td><input type="text" style="width: 320px;" id="ln" name="ln" onBlur="validate_two();"></td> </tr> <tr> <td align="left">*Email address</td> <td align="right"><span id="result"></span></td> <td><input type="text" style="width: 320px;" id="mailfield" name="email" onBlur="startRequest();"></td> </tr> <tr> <td align="left">*Phone number</td> <td align="right"><span id="valid_three"></span></td> <td><input type="text" style="width: 320px;" id="pn" name="pn" onBlur="validate_three();"></td> </tr> <tr> <td align="left">*City/Town</td> <td align="right"><span id="valid_four"></span></td> <td><input type="text" style="width: 320px;" id="c" name="c" onBlur="validate_four();"></td> </tr> <tr> <td></td> <td></td> <td> <select name="s"> <option value="AL">Alabama <option value="AK">Alaska <option value="AZ">Arizona <option value="AR">Arkansas <option value="CA">California <option value="CO">Colorado <option value="CT">Connecticut <option value="DE">Delaware <option value="FL">Florida <option value="GA">Georgia <option value="HI">Hawaii <option value="ID">Idaho <option value="IL">Illinois <option value="IN">Indiana <option value="IA">Iowa <option value="KS">Kansas <option value="KY">Kentucky <option value="LA">Louisiana <option value="ME">Maine <option value="MD">Maryland <option value="MA">Massachusetts <option value="MI">Michigan <option value="MN">Minnesota <option value="MS">Mississippi <option value="MO">Missouri <option value="MT">Montana <option value="NE">Nebraska <option value="NV">Nevada <option value="NH">New Hampshire <option value="NJ">New Jersey <option value="NM">New Mexico <option value="NY">New York <option value="MC">North Carolina <option value="ND">North Dakota <option value="OH">Ohio <option value="OK">Oklahoma <option value="OR">Oregon <option value="PA">Pennsylvania <option value="RI">Rhode Island <option value="SC">South Carolina <option value="SD">South Dakota <option value="TN">Tennessee <option value="TX">Texas <option value="UT">Utah <option value="VT">Vermont <option value="VA">Virginia <option value="WA">Washington <option value="WV">West Virginia <option value="WI">Wisconsin <option value="WY">Wyoming </select> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td></td> <td></td> <td><span id="error"></span></td> </tr> <tr> <td valign="top">*Anti-Spam Verification</td> <td></td> <td id="reCaptcha"></td> </tr> </table> </td> <td valign="top"> <table cellspacing="5"> <tr> <td align="left">*Affiliation</td> <td align="right"><span id="valid_five"></span></td> <td><input type="text" style="width: 320px;" id="affl" name="affl" onBlur="validate_five();"></td> </tr> <tr> <td align="left">*Research Area:</td> <td align="right"><span id="valid_six"></span></td> <td><input type="text" style="width: 320px;" id="ra" name="ra" onBlur="validate_six();"></td> </tr> <tr> <td valign="top" align="left">*Research Overview</td> <td align="right"><span id="valid_seven"></span></td> <td><textarea cols="38" rows="6" id="ro" name="ro" onKeyDown="limitText(this.form.ro,this.form.countdown,500)" onKeyUp="limitText(this.form.ro,this.form.countdown,500)" onBlur="validate_seven();"></textarea></td> </tr> <tr> <td></td> <td></td> <td><font size="1">You have <input readonly type="text" name="countdown" size="1" value="500"> characters remaining.</font></td> </tr> <tr> <td align="left">*Talk Availability</td> <td></td> <td> <input type="radio" name="ta" value="In person">In person <input type="radio" name="ta" value="Online">Online <input type="radio" name="ta" value="Both" checked>Both </td> </tr> <tr> <td align="left" valign="top">Links</td> <td></td> <td> <table id="linkTable" border="0"> <td><input type="text" style="width: 320px;" name="link"></td> <td><div id="result"></div></td> </table> </td> <td align="left" valign="top"><input type="button" value="Add Link" onclick="addLink('linkTable')"></td> </tr> <tr> <td></td> <td><span style="color: red;"></span></td> </tr> </table> </td> </tr> </table> <br /> <input type="submit" id="submit" name="submit" value="Submit Form"> </form> Javascript file: Code: /* * script.js - ajax and table functions */ var xmlHttp; // global instance of XMLHttpRequest var xmlHttp2; // second for captcha functions var validAjax = new Boolean(); var validCaptcha = new Boolean(); var valid_one = new Boolean(); var valid_two = new Boolean(); var valid_three = new Boolean(); var valid_four = new Boolean(); var valid_five = new Boolean(); var valid_six = new Boolean(); var valid_seven = new Boolean(); function init() { showRecaptcha('reCaptcha'); // Separate booleans for AJAX funcs validAjax = false; validCaptcha = false; // Booleanse for fields that don't require servlet validation valid_one = false; valid_two = false; valid_three = false; valid_four = false; valid_five = false; valid_six = false; valid_seven = false; } function showRecaptcha(element) { Recaptcha.create("6Le1a8ESAAAAAGtxX0miZ2bMg0Wymltnth7IG-Mj", element, {theme: "red", callback: Recaptcha.focus_response_field}); } function validate_form() { if (valid_one && valid_two && valid_three && valid_four && validEmail) { startCaptchaRequest(); if (validCaptcha) { return true; } } else { alert("Submission contains errors. Please fill out all required fields before submitting."); return false; } } function validate_one() { if (document.getElementById("fn").value == 0) { valid_one = false; document.getElementById("valid_one").innerHTML = "No"; } else { valid_one = true; document.getElementById("valid_one").innerHTML = ""; } } function validate_two() { if (document.getElementById("ln").value == 0) { valid_two = false; document.getElementById("valid_two").innerHTML = "No"; } else { valid_two = true; document.getElementById("valid_two").innerHTML = ""; } } function validate_three() { if (document.getElementById("pn").value == 0) { valid_three = false; document.getElementById("valid_three").innerHTML = "No"; } else { valid_three = true; document.getElementById("valid_three").innerHTML = ""; } } function validate_four() { if (document.getElementById("c").value == 0) { valid_four = false; document.getElementById("valid_four").innerHTML = "No"; } else { valid_four = true; document.getElementById("valid_four").innerHTML = ""; } } function validate_five() { if (document.getElementById("affl").value == 0) { valid_five = false; document.getElementById("valid_five").innerHTML = "No"; } else { valid_five = true; document.getElementById("valid_five").innerHTML = ""; } } // //function validate_six() { // if (document.getElementById("ra").value == 0) { // valid_six = false; // document.getElementById("valid_six").innerHTML = "No"; // } // else { // valid_six = true; // document.getElementById("valid_six").innerHTML = ""; // } //} // //function validate_seven() { // if (document.getElementById("ro").value == 0) { // valid_seven = false; // document.getElementById("valid_seven").innerHTML = "No"; // } // else { // valid_seven = true; // document.getElementById("valid_seven").innerHTML = ""; // } //} function addLink(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell = row.insertCell(0); var element1 = document.createElement("input"); element1.type = "text"; element1.name = "link" + rowCount; element1.style.width = "320px"; cell.appendChild(element1); } function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } function createXmlHttpRequest() { if(window.ActiveXObject) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } } function startRequest() { createXmlHttpRequest(); var param1 = document.getElementById('mailfield').value; if (param1 == "") { validEmail = false; document.getElementById("result").innerHTML = "Blank"; } else { xmlHttp.open("GET", "http://localhost:1979/PolarSpeakers/servlet/mailCheck.do?e=" + param1, true) xmlHttp.onreadystatechange = handleStateChange; xmlHttp.send(null); } } function handleStateChange() { if(xmlHttp.readyState==4) { if(xmlHttp.status==200) { var message = xmlHttp.responseXML .getElementsByTagName("valid")[0] .childNodes[0].nodeValue; if (message == "Unregistered") { validEmail = true; document.getElementById("result").style.color = "green"; } else { validEmail = false; document.getElementById("result").style.color = "red"; } document.getElementById("result").innerHTML = message; } else { alert("Error checking e-mail address - " + xmlHttp.status + " : " + xmlHttp.statusText); } } } function createCaptchaRequest() { if(window.ActiveXObject) { xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp2=new XMLHttpRequest(); } } function startCaptchaRequest() { alert('made it to captcha requeswt'); createCaptchaRequest(); var param1 = Recaptcha.get_challenge(); var param2 = Recaptcha.get_response(); xmlHttp2.open("POST", "http://localhost:1979/PolarSpeakers/servlet/captchaCheck.do?c=" + param1 + "&r=" + param2, true) xmlHttp2.onreadystatechange = handleStateChangeCaptcha; xmlHttp2.send(null); } function handleStateChangeCaptcha() { if(xmlHttp2.readyState==4) { if(xmlHttp2.status==200) { var message = xmlHttp2.responseXML .getElementsByTagName("result")[0] .childNodes[0].nodeValue; if (message == "Valid") { alert("captcha valid"); validCaptcha = true; } else { document.getElementById("error").innerHTML = message; validCaptcha = false; } } else { alert("Error checking captcha validity - " + xmlHttp2.status + " : " + xmlHttp2.statusText); } } } Hello, I have two problems. Firstly I am trying to make a form with client side validation but I have come across a problem. I need to validate the whole form under just one button but for validating email and phone number I have two different buttons and I am not sure how to make all the code run under just one button when it is submitted. The second problem is with validating the phone number. I am sure the code and javascript is fine, but for some reason it will not work. Here is my code: HTML 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"/> <script type="text/javascript" src="client_validation.js" /> </script> <link rel="stylesheet" type="text/css" href="Client validation.css" /> <title> Client Validation </title> </head> <body> <form name="contact_form" method="post" action="submit" onsubmit="return validate_form ( );"> <h3><strong>Client Validation</strong></h3> <p>Your Name: <input type="text" name="text1"></p> <p>Your Last Name: <input type="text" name="text2"></p> <p>Email: <input type="text" id="email" name="text3"></p> <p>Phone: <input type="text" name="text4"></p> <p>Address: <textarea cols="20" rows="5" name="text5"></textarea></p> <p>Do you agree to the Terms and Conditions? <input type="checkbox" name="text6" value="Yes"> Yes <p><input type="submit" name="send" value="Send Details"></p> </form> Your Email: <form id="form_id" method="post" action="action.php" onsubmit="javascript:return validate('form_id','email');"> <input type="text" id="email" name="email" /> <input type="submit" value="Submit" /> <form method="post" action="data.php" name="form1"> <p>Enter Number <input type="text" name="phoneNo"></p> <input type="button" name="btn1" value="submit" onClick="CheckNumber()"> </body> </html> JAVASCRIPT Code: function validate_form ( ) { valid = true; if ( document.contact_form.text1.value == "" ) { alert ( "Please fill in the 'Your First Name' box." ); valid = false; } if ( document.contact_form.text2.value == "" ) { alert ( "Please fill in the 'Your Last Name' box." ); valid = false; } if ( document.contact_form.text5.value == "" ) { alert ( "Please fill in your address." ); valid = false; } if ( document.contact_form.text6.checked == false ) { alert ( "Please check the Terms & Conditions box." ); valid = false; } return valid; } function validate(form_id,email) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = document.forms[form_id].elements[email].value; if(reg.test(address) == false) { alert('Invalid Email Address'); return false; } } function CheckNumber() { var PhoneNumber=document.form1.phoneNo.value; for (var i=0; i<PhoneNumber.length; i++) { var c=PhoneNumber.charAt(i); if (!(c>0 || c<9)){ alert("This is not a valid Phone Number"); break; } } } I hope you guys can help. Thank you Hi people, I need help as follows: On the server side I have a php generated session parameter. I need to pass it to javascript on the client side page. I saw on the web the following solution: <script language="JavaScript"> var mySessionVar="<%= Session["MySessionVar"] %>"; </script> I tried it but it did not work. I could not find any explanation of this syntax - will appreciate one. Any suggestions, maybe in another way? Thanks Hello, and thank you for taking the time to read over my thread. I'm pretty new with Javascript coding and have been working with an example script for a new membership registration form. The original form seemed to have worked for most intents and purposes but it only contained one entry for a password field. Naturally I felt it needed a conformation field and have tried to stick one in, which is where I ran into problems. I successfully made the script throw an alert box if the two forms are the same, but it then throws another alert box of undefined function as well as throwing the same undefined function alert box even if the fields are a match. Hopefully a knowledgeable person could take a quick look at this and kindly inform me of where I'm going wrong? The code contains two of my numerous attempts to make it work (one commented out, it was easier to remember different things I have tried before to leave then in but commented out, I'm sure you all are quite familiar with that idea). Anyhow, here's the code, thank you in advance. 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>Register</title> <link href="css/master.css" rel="stylesheet" type="text/css" /> <style> .signup {border:1px solid #999999}</style> <script> function validate(form) { fail = validateFirstname(form.firstname.value) fail += validateSurname(form.surname.value) fail += validateUsername(form.username.value) fail += validatePassword(form.password.value) fail += validateConfirmpass(form.confirmpass.value) fail += validateAge(form.age.value) fail += validateEmail(form.email.value) if (fail == "") return true else { alert(fail); return false } } </script> <script> function validateFirstname(field) { if (field == "") return "No First name entered. \n" return "" } function validateSurname(field) { if (field == "") return "No Surname entered. \n" return "" } function validateUsername(field) { if (field == "") return "No Username was entered. \n" else if (field.length < 5) return "Usernames must be at least 5 characters. \n" else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ are valid in Usernames. \n" } function validatePassword(field) { if (field == "") return "No Password was entered. \n" else if (field.length < 6) return "Passwords must be at least 6 characters. \n" else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) || !/[0-9]/.test(field)) return "For your account security Passwords require atleast one uppercase, one lowercase, and one number to be valid. \n" } function validateConfirmpass() { var p1 = document.getElementById('password').value; var p2 = document.getElementById('confirmpass').value; if (p1 !== p2) alert("The password fields do not match."); } //function validateConfirmpass(field) { // var password = document.getElementById('password').value; // var confirmpass = document.getElementById('confirmpass').value; // if (password !== confirmpass) { // return "The password and confirmation do not match. \n" // } //} function validateAge(field) { if (isNaN(field)) return "No Age was entered.\n" else if (field < 18 || field >110) return "Age is required to be between 18 and 110 years. \n" return "" } function validateEmail(field) { if (field == "") return "No Email was entered. \n" else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The Email address entered is invalid. \n" return "" } </script> </head> <body> <table class="signup" border="0" cellpadding="2" cellspacing="5"> <th colspan="2" align="center">Registration Form</th> <form method="post" action="tnssignup.php" onsubmit="return validate(this)"> <tr><td>First name</td><td><input type="text" maxlength="32" name="firstname" /></td> </tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td> </tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td> </tr><tr><td>Password</td><td><input type="text" maxlength="12" id="password" name="password" /></td> </tr><tr><td>Confirm Password</td><td><input type="text" maxlength="12" id="confirmpass" name="confirmpass" /></td> </tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td> </tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td> </tr><tr><td colspan="2" align="center"> <input type="submit" value="Register" /></td> </tr></form></table> </body> </html> I know that Javascript is client side, but I'd like to know the best way to populate HTML drop downs in real time based on information typed in the other HTML form fields with information found on the server as opposed to the client. For instance if a user wants to select certain files located in a directory on the server, as they type in the pathname supposedly containing the files the drop downs continually refresh themselves with the server files listed in that directory (if it exists, and apache has permissions to see what's inside) as if it was showing client files instead. What would be nice is if my browser could continually query the server for some of its private information and not have to refresh itself to obtain it, whether that means the server-side would have to continually refresh itself makes no difference to me as long as the client-side doesn't have to. But I guess this is not possible because no matter what you would have to at least refresh the client-side page once? Submitting the form to a CGI or PHP script would not work because I need this functionality to help populate the form BEFORE I send it. I would like to not have to press a button to update the form every time I change the pathname and need to update the drop downs since this would be annoying. I'm open to anything that could do this or something similar not just Javascript. I'm not sure if you could accomplish this by converting the HTML page to CGI/PHP and having it continually reload itself without refreshing the page? I'm not worried about any security risks this may pose because: 1) The server is located on company intranet which is firewalled 2) I could always password protect and encrypt all transmissions, making sure only authorized users use the app I wish to change the dynamic text in a javascript to that which is in a MySQL database using PHP. this is then used in a flash scroller. currently i have hard coded the text in the javascript file. is there a way to have PHP run in the javascript file before it is sent to the endusers? or another way ? I am developing a mobile app. I have a script that will read the contents of a csv into an array. It works great, however I am not sure how to take that array and insert it into a db. The following is the script that reads the csv -- function IO(U, V) { var X = !window.XMLHttpRequest ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest; X.open(V ? "PUT" : "GET", U, false); X.setRequestHeader("Content-Type", "text/html"); X.send(V ? V : ""); return X.responseText; } var mycells = IO('data.csv').split(/\n/g).map(function(a){return a.split(/\t/g)} ) I want to insert the array 'mycells' into the db but do not know what the correct syntax would be. t.executeSql('INSERT INTO mytable (name, phone, street, city, state) VALUES (????????????... Thanks for any helps that is sent my way! Hi, I am creating a HTML page and mailing it to the user(client side). This html page contains a Table and a button. On button click, I would like to create another HTML page based on the detail in the table,dynamically on run time and Open the newly created HTML. I need to use javascript to achieve this functionality. I have no Server-Client Configuration. And I need to run the Javscript only on client side to process the First HTML's table data and Create a new HTML page. The output of the javascript should also be put in a table format in the newly created HTML page. Here is some background information: The details from one server would be put into this first HTML along with a button. This HTML page is then mailed to Client side. The javascript in the HTML page then processes the Table data of first HTML. This can only be run at Client Side,once the user clicks the button and moreover I dont have Server-Client Configuration. I am creating a report and mailing it, For formatting purposes and for creating hyperlink to mailid's I chose HTML, Now I am struck here. Could some one please help me out with this. Thanks for your time. Hi everyone, I have been trawling for useful info for a few hours and still have no definitive answer. There is plenty of info about creating server side javascript which can use php/asp to pull in xml etc and process but there is nothing I could find identifying how to do the same thing but with the javascript being client side only, e.g chrome plugin code. From what I currently understand, javascript client side only cannot reach or ask for any services externally. Am I missing something obvious or just trying to do something impossible? Cheers , Aro I have heard that it is wrong to just do client validtion. SO can anyone help me with my form? The code below, has client validation and php and I am not sure that I have got it right. Also I would need to cover server side validation too but have no idea on how to do this. I must say I have very small knowledge of JS. Does anyone know the easiest method of doing forms with php, JS server and client side validation. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta content="en" name="language" /> <meta content="Seniors community venue contact details, Seniors community venue contact form, email, address, and telephone number" name="description" /> <meta content="Seniors community venue contact form, email, telephone, address" name="keywords" /> <title>Seniors Community Venue - Contact details</title> <link href="../styles/mainstyle.css" rel="stylesheet" type="text/css" /> <link href="../styles/navigation.css" rel="stylesheet" type="text/css" /> <link href="../styles/layout.css" rel="stylesheet" type="text/css" /> <link href="http://fonts.googleapis.com/css?family=Cabin|Ubuntu" rel="stylesheet" type="text/css" /> <link href="../styles/form.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../javascript/validate.js"></script> <style type="text/css"> .antispam { display: none; } </style> <script type="text/javascript"> var first = "enquiries"; var last = "seniors260.org";</script> </head> <body> <div id="bodyblock"> <div id="container"> <div id="header"> <div class="indentmenu"> <ul> <li><a href="faqs.html">FAQS</a></li> <li><a href="venue_location.html">Location</a></li> <li><a href="about_us.html">About Us</a></li> <li class="first"><a href="home.html">Home</a></li> </ul> </div> <div class="logo_venue"> <img alt="Seniors Community Venue logo" height="100" src="../images/venue_logo.gif" width="200" title="Return to hompage" /></div> <div class="top2"> <p class="tagtitle">"The best community venue<br /> your money can buy"</p> <address class="top"> 260 Stanstead Road<br /> London SE23 1DD<br /> 020 8699 4977</address> </div></div> <div class="indentmenu2"> <ul> <li><a href="room_hire.html">Room Hire</a></li> <li><a href="testimonials.html">Testimonials</a></li> <li><a href="album.html">Photo Album</a></li> <li class="first2"><a href="venue_donations.html">Donations</a></li> </ul> </div> <div id="content"> <h1>Venue Contact Details</h1> <h2>Contact Form</h2> <div id="form_box"> <form id="form" action="../php_files/submit2.php" onsubmit="return validate()" enctype="multipart/form-data" method="post" name="form_to_email" /> <fieldset> <legend>Contact Form</legend> <p><label for="name"><span>Name</span></label><input id="name" name="name" size="35" type="text" /></p> <p><label for="email"><span>Email</span></label><input id="email" name="email" size="35" type="text" /></p> <p><label for="subject"><span>Subject</span></label><input id="subject" name="subject" size="35" type="text" /></p> <p class="antispam">Leave this empty: <br /> <input name="url" /></p> </fieldset><fieldset> <legend>Message</legend> <textarea id="message" cols="50" name="message" rows="10"></textarea></fieldset><fieldset> All fields Required </fieldset><p> <input id="submit" name="submit" type="submit" value="Submit" /></p> i am making a registration page for my website and for validation using javascript...is there any way to know on my client side javascript enable or not....
I have been interested in APIs in the last time and i want to know exactly how it works from the server side. so i tried to figure out how the client side API working , first step i took the Google Plus One JS client side code and i tried to figure out how it works , mostly i tried to find how it gets connect to the server side. i couldn't find what this whole code doing , mainly because i focused to find Ajax requests , but there is none of them. this is the api I checked : https://apis.google.com/js/plusone.js now , my questions is simple , i want to know how API connect to the server side , do they use AJAX? what exactly they use to send request to server side ? i need you're help to know more on how api working on Client side , mainly on the connect to the server. so , how it get's done? I've been avoiding php and asp trying to do as much client-side as possible, as lightweight as possible, but don't know enough to know if I should go that route. I want to have several js/jquery games, really simple stuff like flash cards, memory games, matching, etc Currently when you do something correctly it adds 5 points like: points+=5; and if you get it wrong lose 3 points: points-=3; At the end of the game it flashes a play again button which resets points and all the cards, and that's it. So I was trying to think of ways to add a global variable that adds the latest score to it, and maybe gives you a random "prize" which would be another variable randomly selected from an array of "prizes", or better yet, "achievements"....between games....on the same domain. I'd like to eventually make something similar to a "crafting" system, where if you have 3 particular achievements you can convert them into some new achievement...I imagine just a function that checks if you have the 3 objects, then if so it adds some 4th object and removes the first 3. I was avoiding server side databases because I was avoiding authentication/user accounts for the time being...I would probably eventually like to let people play games, and if they want to save their scores long term, register an account....but if they don't want to register an account, I'd like them to have the same functionality for that session, where they can play a few games from around the site while accumulating a global score and list of achievement variables. I was messing around with jstorage, but am not sure if it will work for what I'm thinking....it only accepts strings, and I couldn't figure out how to write the variableName.toString() into the jstorage "value" of the key:value pair...it gives me the impression it's more for storing form data as a convenience to the user. So is there a client side variable storage that's simple, lightweight, and works with mobile? Or a way to write .toString() value of objects into jstorage? Or should I just break down and start investigating my server side options? Is there some middle ground where stuff can be done client side, then give the option to register to save that information long term? edit::I'm thinking of my 3 year old nieces ipad games, they're simple drag drop, highlight shapes, pattern association, etc but I want it so each time you play it remembers where you left off...basically a cookie would have been cool if it were bigger and not sent every packet....so kinda a "save-state" and "load-state" functionality.. edit2::sqlite seems like a legitimate option but then reading through it, it gets convoluted how to implement on my bluehost account... Please help with some javascript for client side storage in html5 mobile safari. Here we wish to use local storage [persistent]. The page index.html has a list of links to question pages e.g. question1.html. When question1.html is answered correctly the page goes to answer1.html. From here, the page moves back to index.html by pressing a button. The button has 2 actions: goto index.html place a key/value pair in local storage - e.g. localStorage.setItem("name", "answer1"); On reloading, the index.html page then asks the local storage if the key/value pair ("name" "answer1") is stored. If yes, a new graphic appears next to the link. If no, the old graphic remains. Thank you for any help. Hi All, I'm working on a javascript-only application that queries an in-memory database, at times requests (all internal to the JS app) are lengthy, so I need to post a "Processing..." overlay atop the clicked UI tab to provide user feedback that something is actually happening. For the life of me I cannot figure out how to push the "Processing..." content to the screen while the DB lookup is underway. It appears that there's only one shot at updating the display, and that's when all JS processing has concluded (ie, the data has been looked up and is displayed). Any tips would be greatly appreciated, what I wish to do may not be possible? Thanks in advance for your assistance! JD Hi, I am trying to write a small web app that is used to do some plots for over-the-time-collected data (children's growth measurements). The current objective is to re-use entered data. As I do not want to store anything on the server (which would lead to all the annoying username-password-stuff), nor in cookies, I would like put measurements into a local file and reload them into the HTML entering form. I know and fully appreciate that javascript is not able to read or write files; it is on the other hand obvious that this can be bypassed if I upload the respective file to the server which returns it in an ajax fashion. My main question is now: Is it possible to do some kind of internal upload, that ends up in a read of a local file? Something like a <form method="post" action="localscriptname" ...> with an <input type="file"...> field? Another (off-topic) question: My plots are in PDF format. I accidentally appended some data to the PDF file which did not cause any problems for the pdf readers. Can I rely on the fact that any pdf reader will ignore data after the %%EOF mark, but will keep it if a file is downloaded, directly opened by acroread or whatever, and later saved from the reader program? This would allow it to keep the plot and the raw data in one file and might be helpful for the not-so-computer-affine target audience of my program. Greetings! Hi guys, Been stuck for a few days with this scenario. Any help? The alert box appears on an error. But the submitting won't stop. The details are submitted and the form is processed. Any help is greatly appreciated... Code: <html> <head> <script type="text/javascript" src="email_helper/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode : "textareas", theme : "simple" }); </script> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); } function err_check(){ var email = document.getElementById('to_email').value; if(email.length==0){ alert('Please Enter Email Address'); return false; } var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } email = document.getElementById('cc_email').value; if(email.length != 0){ var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } } var answer = confirm ("Send E-Mail?"); if (!answer){ return false; } } </script> <!-- /TinyMCE --> <style type="text/css"> body, table, td, th{ background-color:#CCCCCC; font-family: Arial; font-size:14px; } .que{ font-weight:bold; } </style> </head> <body> <form method="post" enctype="multipart/form-data"> <?php include 'library/database.php'; include 'library/opendb.php'; $query = mysql_query("SELECT email,contact,mobile FROM users WHERE user_id='$uid'") or die(mysql_error()); $row = mysql_fetch_row($query); $from_email = $row[0]; $from_person = $row[1]; $from_mobile = $row[2]; $query = mysql_query("SELECT customer_id FROM campaign_summary WHERE camp_id='$camp_id'") or die(mysql_error()); $row = mysql_fetch_row($query); $cusid = $row[0]; $query = mysql_query("SELECT email FROM client_info WHERE comp_id='$cusid'") or die(mysql_error()); $row = mysql_fetch_row($query); $toer = $row[0]; include 'library/closedb.php'; ?> <table width="100%" border="0"> <tr><td rowspan="4"><input type="submit" name="send_email" id="send_email" style="height:50px; width:100px;" value="SEND" onClick="return err_check();" /></td><td><span class="que">From : </span></td><td colspan="3"><?php echo $from_email; ?><input type="hidden" name="from_mail" id="from_mail" /><input type="hidden" name="camp_id" id="camp_id" value="<?php echo $camp_id;?>"/></td></tr> <tr><td><span class="que">To : </span></td><td colspan="3"><input name="to_email" id="to_email" style="width:250px;" value="<?php echo $toer;?>"/></td></tr> <tr><td><span class="que">CC : </span></td><td colspan="3"><input name="cc_email" id="cc_email" style="width:250px;"/></td></tr> <tr><td><span class="que">Subject : </span></td><td colspan="3"><input style="width:300px;" name="subject" id="subject" /></td></tr> <tr><td rowspan="1" colspan="2"> </td><td><input type="checkbox" name="ori_pdf" id="ori_pdf" checked /> PDF Quotation</td><td> </td><td> </td></tr><tr><td colspan="2"><span class="que">Credit Application</span></td><td><input type="checkbox" name="corporate" id="corporate"/>Corporate</td><td><input type="checkbox" name="individual" id="individual" />Individual</td><td><input type="checkbox" name="cash" id="cash" />Cash Account</td> </tr> <tr> <td colspan="2" rowspan="3"></td><td><input type="checkbox" name="tabloid" id="tabloid" />Tabloid Example</td> <td><input type="checkbox" name="broadsheet" id="broadsheet" />Broadsheet Example</td></tr> <tr><td><input type="checkbox" name="colmt" id="colmt" />Column Sizes Tabloid</td> <td><input type="checkbox" name="colmb" id="colmb" />Column Sizes Broadsheet</td></tr> <tr><td><input type="checkbox" name="maps" id="maps" />Maps / Distribution</td><td colspan="2" align="right">External Attachments <input id="upload_file" name="upload_file" type="file"/> </td></tr> <tr><td colspan="2"><span class="que">Message :</span></td><td colspan="3"> <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 100%"> <?php echo "<br><br><br>" . $from_person . "<br>" . $from_mobile; ?> </textarea> </td></tr> </table> </form> </body> </html> I have a form validation script that runs perfect. Now i want to add one more field to the form and want to make some fields "required" but i dont know how to do this. Please help me. I am also attaching the relevant files. Thanks in advance. Fields to add: 1. Social Security Number (Same as Home Telephone but allows 3 digits in 1st field, 2 in 2nd and 4in 3rd field (123)-(12)-(1234)) Fields to make "required" : Social Security Number First Name Last Name The Script Code: var phoneRegEx = /^(?:(?:\(?(?:(?:[246-8](?:(?:[02-8][0-9])|(?:1[02-9])))|(?:3(?:(?:[02-68][0-9])|(?:1[02-9])))|(?:5(?:(?:[02-46-8][0-9])|(?:5[0-46-9])|(?:1[02-9])))|(?:9(?:(?:[02-578][0-9])|(?:1[02-9]))))\)?)(?:[\- ]?)(?:(?:700(?:[\- ]?)(?:(?:[0-35-9][0-9]{3})|(?:4[02-9][0-9]{2})|(?:41[0-35-9][0-9])|(?:414[02-9])))|(?:(?:(?:[23468][02-9][0-9])|(?:[2-9]1[02-9])|(?:5(?:(?:5[0-46-9])|(?:[02346-9][0-9])|(?:1[02-9])))|(?:7(?:(?:[2-9][0-9])|(?:0[1-9])|(?:1[02-9])))|(?:9(?:(?:[0234689][0-9])|(?:1[02-9])|(?:5[1-7])|(?:7[0-5789]))))(?:[\- ]?)(?:[0-9]{4}))))$/; var error // used to store RowNames for errored elements. var isOptRequired = false; function ValidateQuoteRequest(frm) { if(isBrowserCompatible()) { error = new Array(); CheckDropDown('state', 'row_state', frm); CheckDropDown('Month', 'row_date', frm); CheckDropDown('Day', 'row_date', frm); CheckDropDown('Year', 'row_date', frm); CheckDate('Month', 'Day','Year', 'row_date', frm, 'True'); CheckDropDown('Sex', 'row_sex', frm); CheckDropDown('Height_Feet', 'row_Height', frm); CheckDropDown('Height_Inches', 'row_Height', frm); CheckIntegerField('Weight', 'row_Height', frm, 'True'); CheckDropDown('Tobacco', 'row_tobacco', frm); CheckFrequency('Frequency', 'row_tobaccotype', frm, 'True'); CheckPhone('workphone,homephone', 'row_workphone,row_homephone', frm, 'False'); CheckEmail('email', 'row_email', frm, 'False'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateRequestApplication(frm) { if(isBrowserCompatible()) { error = new Array(); CheckTextField('firstname', 'row_firstname', frm,); CheckTextField('lastname', 'row_lastname', frm); CheckTextField('address', 'row_address', frm); CheckTextField('city', 'row_city', frm); CheckTextField('state', 'row_state', frm); CheckZip('zip', 'row_state', frm, 'True'); CheckPhone('work_phone_number_,home_phone_number_,cell_phone_number_', 'row_work_phone_number_,row_home_phone_number_,row_cell_phone_number_', frm, 'True'); CheckNumericField('work_phone_number_4', 'row_work_phone_number_', frm, 'False'); CheckEmail('email', 'row_email', frm, 'True'); CheckDropDown('premium_quoted', 'row_premium_quoted', frm); CheckRadioButton('Residency', 'row_Residency', frm); CheckRadioButton('spouse_policy', 'row_spouse_policy', frm); CheckSpouseTextField('spouse_first_name', 'row_spouse_first_name', frm); CheckSpouseTextField('spouse_last_name', 'row_spouse_last_name', frm); CheckDropDown('AgentID', 'row_AgentID', frm); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateRBCRequestApplication(frm) { if(isBrowserCompatible()) { error = new Array(); CheckTextField('firstname', 'row_firstname', frm); CheckTextField('lastname', 'row_lastname', frm); CheckTextField('address', 'row_address', frm); CheckTextField('city', 'row_city', frm); CheckTextField('state', 'row_state', frm); CheckZip('zip', 'row_state', frm, 'True'); CheckPhone('work_phone_number_', 'row_work_phone_number_', frm, 'True'); CheckEmail('email', 'row_email', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateRBCQuoteRequest(frm) { if(isBrowserCompatible()) { error = new Array(); CheckDropDown('state', 'row_state', frm); CheckDropDown('Sex', 'row_Sex', frm); CheckDate('Month', 'Day','Year', 'row_date', frm, 'True'); CheckDropDown('Amount', 'row_Amount', frm); CheckRadioButton('coverageTerm', 'row_coverageTerm', frm); CheckRadioButton('tobacco', 'row_tobacco', frm); CheckTextField('firstname', 'row_firstname', frm); CheckTextField('lastname', 'row_lastname', frm); CheckPhone('home_phone_number_', 'row_home_phone_number_', frm, 'True'); CheckEmail('email', 'row_email', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateHealth(frm) { if(isBrowserCompatible()) { error = new Array(); CheckEmail('Email', 'row_Email', frm, 'True'); CheckZip('ZipCode', 'row_ZipCode', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateHome(frm) { if(isBrowserCompatible()) { error = new Array(); CheckEmail('Email', 'row_Email', frm, 'True'); CheckZip('ZipCode', 'row_ZipCode', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateLTC(frm) { if(isBrowserCompatible()) { error = new Array(); CheckDropDown('state', 'row_state', frm); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } function ValidateAuto(frm) { if(isBrowserCompatible()) { error = new Array(); CheckZip('zipcode', 'row_zipcode', frm, 'True'); if (error.length > 0) { //turn on error header and scroll page to error header document.getElementById("contentError").style.display = ""; location = '#contentError'; return false; } else { document.getElementById("contentError").style.display = "none"; return true; } } else //browser not compatible { return true; } } //------- function CheckAnnualIncome (ElmtName, RowName, frm,isReq) { if(!frm.elements[ElmtName + '_decline'].checked) CheckNumericField (ElmtName,RowName, frm, isReq); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckTextField (ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; if(trim(frm.elements[ElmtName].value) == '') ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //---- function CheckSpouseTextField (ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; for(var i=0;i < frm.spouse_policy.length; i++) { if(frm.spouse_policy[i].checked && frm.spouse_policy[i].value == 'yes') { CheckTextField (ElmtName, RowName, frm); }else{ removeErrorFormatting(ElmtName, RowName, frm); } } } //------ function CheckNumericField(ElmtName, RowName, frm, isReq) { if (frm.elements[ElmtName].value != '' || isReq.toLowerCase() == 'true') { var val = frm.elements[ElmtName].value.replace(/,/g,''); val = val.replace('$', ''); if(parseFloat(val)!=(val*1) || val == '') ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } else { removeErrorFormatting(ElmtName, RowName, frm); } } function CheckIntegerField(ElmtName, RowName, frm, isReq) { if (frm.elements[ElmtName].value != '' || isReq.toLowerCase() == 'true') { if(frm.elements[ElmtName].value.indexOf('.') != -1 || (frm.elements[ElmtName].value % 1) != 0 || frm.elements[ElmtName].value == '') ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } else { removeErrorFormatting(ElmtName, RowName, frm); } } //----- function CheckEmail (ElmtName, RowName, frm, isReq) { //add for optimost required field testing. if(isOptRequired) isReq = 'true'; var regEx; regEx = /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/; if(!regEx.test(frm.elements[ElmtName].value) && (frm.elements[ElmtName].value != '' || isReq != 'False')) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckDate(ElmtMonth, ElmtDay, ElmtYear, RowName, frm, isReq) { var Day = frm.elements[ElmtDay].options[frm.elements[ElmtDay].selectedIndex].value; var Month = frm.elements[ElmtMonth].options[frm.elements[ElmtMonth].selectedIndex].value - 1; var Year = frm.elements[ElmtYear].options[frm.elements[ElmtYear].selectedIndex].value; var DateObj = new Date(Year,Month,Day); if ( DateObj.getMonth() != Month) { ThrowError(RowName, RowName, frm); } else { removeErrorFormatting(RowName, RowName, frm); } } //------- function CheckZip(ElmtName, RowName, frm, isReq) { var regEx regEx = /^\d{5}$|^\d{5}-\d{4}$/; if(!regEx.test(frm.elements[ElmtName].value) && (frm.elements[ElmtName].value != '' || isReq != 'False')) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------ function CheckDropDown(ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; if(frm.elements[ElmtName].options.selectedIndex == 0) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckRadioButton(ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; var radioChecked = false; for(var i=0;i < frm.elements[ElmtName].length; i++) { if(frm.elements[ElmtName][i].checked) { radioChecked = true; break; } } if(!radioChecked) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckCheckboxes(ElmtName, RowName, frm) { if (!frm.elements[ElmtName]) return; var checkboxChecked = false; for(var i=0;i < frm.elements[ElmtName].length; i++) { if(frm.elements[ElmtName][i].checked) { checkboxChecked = true; break; } } if(!checkboxChecked) ThrowError(ElmtName, RowName, frm); else removeErrorFormatting(ElmtName, RowName, frm); } //------- function CheckPhone(ElmtNames, RowNames, frm, isReq) { //add for optimost required field testing. if(isOptRequired) isReq = 'true'; checkPhoneNumbers(ElmtNames, RowNames, frm, isReq) } //------ function CheckFrequency(ElmtName, RowName, frm) { var Tobacco = new Array(3,4,5,6,7,8); var ThrowErrorFlag = false; for(i = 0; i < Tobacco.length; i++) { if(Tobacco[i] == frm.elements["Tobacco"].options[frm.elements["Tobacco"].selectedIndex].value && frm.elements["Frequency"].options.selectedIndex == 0) { ThrowError("Frequency", RowName, frm); ThrowErrorFlag = true; break; } } if(!ThrowErrorFlag) removeErrorFormatting(ElmtName, RowName, frm); } function CheckTextArea(field, maxlen) { if (field.value.length > maxlen) { field.value = field.value.substring(0, maxlen); alert('Only 1000 characters allowed. Your input has been truncated to 1000 characters'); } } //------ function ThrowError(ElmtName, RowName, frm) { if(!eval("document.getElementById('" + RowName + "')")) return; applyErrorFormatting(ElmtName, RowName,frm) error[error.length] = RowName; } //------ function applyErrorFormatting(fldName, RowName,frm) { tableRow = eval("document.getElementById('" + RowName + "')"); tableRow.className = "error2"; } //----- function removeErrorFormatting(fldName, RowName,frm) { var isSharedRow = CheckForSharedRow(RowName) // call function to handle fields that share the same row if(isSharedRow) return true; tableRow = eval("document.getElementById('" + RowName + "')"); if(tableRow) tableRow.className = "quoter"; } function CheckForSharedRow(RowName) { for(var i=0;i<error.length;i++) { if(error[i] == RowName) return true; } return false; } function isBrowserCompatible() { if(document.getElementById) return true; else return false; } function trim(str) { return str.replace(/^\s*|\s*$/g,""); } //------ function OpenWindow(name,filename,height,width,parameters) { var hwin = window.open(filename,name,"height=" + height + ",width=" + width + "," + parameters); hwin.focus(); } //----- function StandardPopup(pagePath) { OpenWindow("", pagePath, 450, 300, ""); } //------ Code for the form: Code: <form action="#" method="get" onsubmit="return ValidateQuoteRequest(this);" name="FrontPage_Form"> <tr class="quoter" id="row_state"> <td align="right" nowrap=""><a href="javascript:popUp('state')" title="">State</a></td> <td colspan="2"> <select name="state" size="1" tabindex="12"> <option value="-1">Select state...</option> <option value="AK">Alaska</option> </select> </td> </tr> <tr class="quoter" id="row_date"> <td align="right"><a href="javascript:popUp('dob');" title="">Date of Birth</a></td> <td colspan="2"><select name="Month"> <option value="-1">Month</option> <option value="01">Jan</option> </select> <select name="Day"> <option value="-1">Day</option> <option value="01">01</option> </select> <select name="Year" size="1"> <option value="-1">Year</option> <option value="1921">1921</option> </select> </td> </tr> <tr class="quoter" id="row_sex"> <td align="right"><a href="javascript:popUp('gender')" title="">Gender</a></td> <td colspan="2"><select name="Sex" size="1"> <option value="-1">Select...</option> <option value="1">Male</option> </select> </td> </tr> <tr class="quoter" id="row_Height"> <td align="right">Height</td> <td nowrap="" colspan="2"><select name="Height_Feet" size="1"> <option value="-1"></option> </select> ft <select name="Height_Inches" size="1"> <option value="-1"></option> </select> in Weight <input name="Weight" size="3" maxlength="3" value=""> lbs </td> </tr> <tr class="quoter" id="row_tobacco"> <td align="right"><a href="javascript:popUp('tobacco')" title="">Tobacco/ Nicotine Use</a></td> <td colspan="2"><select name="Tobacco" onchange="toggleRow(this,'4,5,6,7,8','row_tobaccotype',document.FrontPage_Form.Frequency)"> <option value="-1">Select...</option> <option value="1">Never used</option> <option value="7">Current user</option> </select></td> </tr> <tr class="quoter" style="display: none; " id="row_tobaccotype"> <td align="right">Type of Tobacco or Nicotine and frequency of use</td> <td colspan="2"><select name="Frequency"> <option value="0" selected="">Please select...</option> <option value="10">Cigarettes, less than 1/2 pack a day</option> </select></td> </tr> <tr class="quoter" id="row_coverage"> <td align="right" class="quoter"><a href="javascript:popUp('calculator','https');" title="">Coverage Amount</a></td> <td><select name="Amount" size="1"> <option value="750000">$750,000</option> </select> <a href="javascript:popUp('calculator');" title="" class="nav-sub" ;=""><img src="./Insurance_files/help.gif" width="16" height="17" alt="" border="0" align="bottom"></a></td><td class="quoter"><a href="javascript:popUp('calculator');" title="">How much life<br>insurance do I need?</a></td> </tr> <tr class="quoter"> <td align="right"><a href="javascript:popUp('term');" title="">Guaranteed Term</a></td> <td class="quoter" colspan="2" id="ProductType"><select name="ProductType" size="1"> <option value="8">10 Years</option> </select></td> </tr> <tr class="quoter" id="row_PreClass"> <td align="right"><a href="javascript:popUp('healthclass');" title="">Health Class</a></td> <td><select name="PreClass" size="1"> <option value="0" selected="">Best Class</option> <option value="2">Preferred</option> </select> <a href="javascript:popUp('healthclass');" title=""><img src="./Insurance_files/help.gif" width="16" height="17" alt="" border="0" align="bottom"></a></td> <td><a href="javascript:popUp('healthclass');" title="">How do I determine<br>my health class?</a><a href="#">*</a></td> </tr> <tr class="quoter" id="row_firstname"> <td align="right"> First Name</td> <td class="quoter" colspan="2"><input name="firstname" size="30" maxlength="50" value=""></td> </tr> <tr class="quoter" id="row_lastname"> <td align="right"> Last Name</td> <td colspan="2"><input name="lastname" size="30" maxlength="50" value=""></td> </tr> <tr class="quoter" id="row_workphone"> <td align="right">Social Security Number</td> <td colspan="2">(<input maxlength="3" name="ssn1" size="3" value="">)-<input maxlength="2" name="ssn2" size="2" value="">-<input name="ssn3" size="4" maxlength="4" value=""></td> </tr> <tr class="quoter" id="row_workphone"> <td align="right">Work Phone</td> <td colspan="2">(<input maxlength="3" name="workphone1" size="3" value="">)-<input maxlength="3" name="workphone2" size="3" value="">-<input name="workphone3" size="4" maxlength="4" value=""></td> </tr> <tr class="quoter" id="row_homephone"> <td align="right">Home Phone</td> <td colspan="2">(<input maxlength="3" name="homephone1" size="3" value="">)-<input maxlength="3" name="homephone2" size="3" value="">-<input name="homephone3" size="4" maxlength="4" value=""></td> </tr> <tr class="quoter" id="row_email"> <td align="right"><a href="javascript:popUp('email','https');">E-mail</a></td> <td colspan="2"><input name="email" size="30" maxlength="80" value=""></td> </tr> <tr> <td colspan="3" align="center" nowrap=""> <input type="image" title="Please click only once." name="Submit" src="./Insurance_files/compare_rates.gif" width="172" height="28" value="Compare Rates Now!" alt="Get Your Life Insurance Quote Now"> </form> Hi i need help with an assignment that validates forms using javascript. Using my instructors example as a guide, i wrote this if you click submit on the example it properly returns false and displays an error message, in my assignment it does nothing but submit to the echo while im trying to get an error message. The assignment is unfinished but i wanted to test out the first bit of code and its not working. Hi Guys, I have trying to validate my form using JavaScript. On blur of the a text box I am calling a function in JavaScript which checks if the text box is empty or not.... If the text box is empty it display an appropriate error message. The issue I am facing is that, for the first time if any user does not enter any value in the text box, the JS function is invoked and an appropriate error message is displayed.... So when the user tried to enter a value in the text box, a drop down list appear from the past forms data. (The drop down value appear because the user has already filled in the form in the past. Hence the Browser remember the data filed in, and displays it as a drop down list.) This allows the user to select any values from the drop down list to fill in the box.* After the user has selected the appropriate value from the drop down and takes its mouse cursor and navigates to another text box in the form, the first error message does not disappear. The form does not recognize that the value filed has already been filled in the first filed.* If the user actually types into the field it recognizes that the text box has a filed is filled. Please may I know how to solve this issue. |