JavaScript - Client Side Javascript Form Validation (uses Ajax) - Form Won't Submit, Help!
I'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); } } } Similar TutorialsHi, 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> I have a simple form and am validating onchange and need a final validation onsubmit. I am displaying a message to the right of the inputbox on error. I'm trying to keep this at DOM 1 compatible and not use any framework. HTML Code: <form id = "myForm" action = "" onsubmit = "return validateForm(this);"> <table class = "table-submit" border = "0"> <tr> <td> Username: </td> <td> <input type = "text" id = "username" size = "30" maxlength = "30" onchange = "validateUsername(this, 'msgUsername')" /> </td> <td id = "msgUsername"> </td> </tr> <tr> <td> Password: </td> <td> <input type = "password" id = "password" size = "30" maxlength = "30" onchange = "validatePassword(this, 'msgPassword')" /> </td> <td id = "msgPassword"> </td> </tr> <tr> <td> </td> <td> <input type = "submit" value = "Submit" /> <input type = "reset" value = "Clear" /> </td> </tr> </table> </form> JavaScript Code: function validateUsername(myItem, myElement) { var dom = document.getElementById(myElement); if (myItem.value.length < 3) { dom.innerHTML = " Username needs to be a minimum of 3 characters! "; return false; } else { dom.innerHTML = ""; return true; } } function validatePassword(myItem, myElement) { var dom = document.getElementById(myElement); if (myItem.value.length < 5) { dom.innerHTML = " Password needs to be a minimum of 5 characters! "; return false; } else { dom.innerHTML = ""; return true; } } function validateForm (itm) { // kind of stuck here... } As you may of noticed, I am a bit stuck on my validateForm() function. The code validates on each inputbox onchange event. Not sure what is the best way to go from here. I thought about doing an If for my both single input box validation, but I would need to send each parameters which is what i was trying to avoid by using this. Would like some suggestions. Hello all I created a form which has a lot of textboxes, checkboxes and select-lists which are getting filled up by the records from a database table. I am basically creating an edit screen for a record. No I want to check all these input elements using javascript validation. I want this to performed when a button "Archive" is pressed. My problem is this "Archive button" needs to be a submit button. This does run the javascript validation but after completing the validation it submits the form. I want that submission should be stopped when the validation is violated. how can I do this? What I want is a button which acts as a default button (triggers the onclick event when I press enter) but submits only if the form is valid. 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 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 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 Hi, I currently have a form which is submitted using a html submit button. I was wondering what the best way is of using ajax to submit the page without the use of a submit button, and when the page submits, a message is displayed saying thank you for your booking. Thanks. plz i want to know how i can make a form validation using AJAX??? i need a sample or an idea of how making my form validation using AJAX thnx alot in advance I am trying to perform an AJAX lookup during form validation onsubmit. It is important that it takes place during submit, but it seems to always return true and allow the form to post even when it should not. I have tried putting the AJAX portion in its own function and having it return true or false to the validation function but also does not seem to work. Here is what the code looks like... Code: $("#companyform").submit(function() { $.ajaxSetup({ cache: false }); $.post("ajax_v2Functions.cfm", { coNum: $("#companyNumber").val() }, function(response) { if(response != "") { alert("That company number is already in use by " + response); $("#companyNumber").focus(); return false; } return false; } , "html"); if($("#companyname").val() == "") { alert("The company name cannot be left blank."); $("#companyname").focus(); return false; } if($("#companyNumber").val() == "") { alert("The company number cannot be left blank."); $("#companyNumber").focus(); return false; } }); 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> he everyone please i want to know how to submit a form using ajax every 5 minutes without reloading page i have a huge form for exams and i need to submit the form without the need to wait until pressing submit because the user may wait to think about the answer a very long time.. so i want to submit the form and at the same time i cant reload the page as it is in normal submit form.. so how i can submit form in the background without letting the user knows that the form is submitted??? Trying to create an eBay listing template with a form on it. The form will allow the buyer to enter in their ebay ID, item number, and 3 choices. Form is complete, using this javascript for validation: Code: <SCRIPT language=javascript> function validate(){ var ebayid= document.getElementById('ebayid').value; var itemnumber= document.getElementById('itemnumber').value; var choice1= document.getElementById('choice1').value; var choice2= document.getElementById('choice2').value; var choice3= document.getElementById('choice3').value; if (!ebayid){ alert('Ebayid is required!'); document.getElementById('ebayid').focus(); return false; } if (!itemnumber){ alert('Item Number is required!'); document.getElementById('itemnumber').focus(); return false; } if (!choice1){ alert('Choice 1 is required!'); document.getElementById('choice1').focus(); return false; } if (!choice2){ alert('Choice 2 is required!'); return false; } if (!choice3){ alert('Choice 3 is required!'); return false; } return true; } </SCRIPT> I like this because it gives a pop up alert box (with definition) if a field is left empty. Upon success though the user is redirected off the page to a success page. I was told that this has to happen because the .php for the form to work is hosted on my site and the user needs to be redirected to my site in order for the form to work. Since this is the case, I was told I could use javascript to open up a separate window for this to happen, thus allowing the buyer to stay on the eBay listing (and to stay compliant with eBay's html/javascript policy). I have pieced together code from numerous forums to actually do this but there is one flaw. Code: <form action="http://www.mysite.com/test.php" method="post" name="testform" id="testform" onsubmit="window.open('', 'success', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes'); javascript:return validate();" rel="nofollow" target="success"/> This code not only opens a new window but it opens the new window on any click to the submit button, even if the validation fails. How do I write this so that the new window is only opened when the validation completes all true and not when the validation returns an error/alert box? Additionally... how do I add to the javascript so that the field "ebayid" requires 6 characters and the "itemnumber" requires 12 numbers? I would also like for the form itself to erase after a successful submission to prevent the user from hitting the submit button 100's of times spamming me with email (if it's possible) Thanks Kemble 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 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> I have a form developed in Dreamweaver CS5 using Spry Assets, I have 2 required fields in the form. One is email the other is phone. I want the user to only have to fill in one or the other, but one or the other needs to be filled out. Here is the form code: [code]<form id="form1" name="form1" method="post" action="http://www.greenhousegraphix.com/GatewayVentures/sendmail.php"> <span id="sprytextfield1"><label>Name</label> <input name="Name" type="text" id="Name" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span></span><br /> <span id="sprytextfield3"><label>Title</label> <input name="Title" type="text" id="Title" size="45" /> </span><br /> <span id="sprytextfield2"><label>Company</label> <input name="Company" type="text" id="Company" size="45" /> </span><br /> <span id="sprytextarea1"><label>Address</label> <textarea name="Address" id="Address" cols="39" rows="2"></textarea> </span><br /> <span id="sprytextfield4"><label>City</label> <input name="City" type="text" id="City" size="45" /> </span><br /> <span id="sprytextfield5"><label>State</label> <input name="State" type="text" id="State" size="45" /> </span><br /> <span id="sprytextfield6"><label>Zip</label> <input name="Zip" type="text" id="Zip" size="45" /> <span class="textfieldInvalidFormatMsg">Invalid format.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMinValueMsg">The entered value is less than the minimum required.</span></span><br /> <span id="sprytextfield7"><label>Phone</label> <input name="Phone" type="text" id="Phone" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br /> <span id="sprytextfield8"><label>Email</label> <input name="Email" type="text" id="Email" size="45" /> <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br /> <span id="sprytextarea2"><label>Message</label> <textarea name="Message" id="Message" cols="39" rows="6"></textarea> </span><br /> <input name="SUBMIT" type="image" class="marginleft95px" src="images/submit.jpg" /> </form> </div> <div id="apDiv2"><img src="images/contact-us-keyboard.jpg" width="318" height="230" alt="contact us" /></div> <div id="apDiv3"><img src="images/contact-us.jpg" width="318" height="230" alt="contact us" /></div> </div></div> <script type="text/javascript"> var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["blur"]}); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {isRequired:false}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "none", {isRequired:false}); var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "none", {isRequired:false}); var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5", "none", {isRequired:false}); var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6", "zip_code", {isRequired:false}); var sprytextfield7 = new Spry.Widget.ValidationTextField("sprytextfield7", "phone_number", {validateOn:["blur"], hint:"(999) 999-9999"}); var sprytextfield8 = new Spry.Widget.ValidationTextField("sprytextfield8", "email", {validateOn:["blur"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {isRequired:false}); var sprytextarea2 = new Spry.Widget.ValidationTextarea("sprytextarea2", {isRequired:false}); </script>[code] Please help!! |