JavaScript - Jquery Form Validation Seems To Be Preventing Form Submission
I have been hard at work coding a fancy JQuery form validation script. Problem is, when I run validation on my form, it seems to work, but no email is sent. But when I disable validation, the email sends just fine. I am fairly new to JavaScript, and need some help pinpointing where my error is.
Here is the code. Code: // BEGIN JAVASCRIPT $(function(){ //original field values var field_values = { //id : value 'name' : 'your name', 'email' : 'your email', 'yourmessage' : 'I would like to inquire about' }; //inputfocus $('input#name').inputfocus({ value: field_values['name'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('textarea#yourmessage').inputfocus({ value: field_values['yourmessage'] }); //form validation $('form').submit(function validateForm(){ return false }); // removing this return false seems to mess up validation $('#submit').click(function(){ //remove classes $('#sendamessage input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields1 = $('#sendamessage input[type=text],#sendamessage textarea'); var error = 0; fields1.each(function(){ var value = $(this).val(); if( value.length<2 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); // css class $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); // css class } }); if(!error) { // this is where I get confused. How do I make this send the form? alert('Data sent'); }); } }); }); // END JAVASCRIPT <form method="post" action="" onsubmit="return validateForm()" > <input type="hidden" name="ccf_customhtml" value="1" /> <input type="hidden" name="success_message" value="Thank you for filling out our form!" /> <input type="hidden" name="destination_email" value="dauidus@gmail.com" /> <input type="hidden" name="required_fields" value="" /> <label for="name">Name</label> <input type="text" name="name" id="name" value="your name" /> <label for="email">Email</label> <input type="text" name="email" id="email" value="your email" /> <label for="yourmessage">Your Message</label> <textarea name="yourmessage" id="yourmessage" value="I would like to inquire about" style="margin-bottom:20px;" />I would like to inquire about</textarea> <input class="send submit" id="submit" type="submit" value="" style="position: relative; bottom: -70px; left: 25px; " /> </form> I am using a WordPress plugin to automatically send the contents of the form to email. It works without the javascript enabled. But when I turn on JS the form gets validated, but no email is sent. Please let me know if I should include anything else here... I've been looking at this code so much that I'm having a hard time doing it with fresh eyes. The problem page is on http://new.dauidusdesign.com/contact/. FYI, I am also looking to make this work with the 'request a quote' link on the same page. Cheers! -Dave Similar TutorialsHello there, I hope you might be able to help me with an issue I'm having getting a form to validate before submission. I've been trying to figure out where I'm going wrong but being relatively new to javascript I'm obviously missing something. I have a form which calls one of two validation scripts with onBlur for each field (I've only included one of each field, there are 8 fields in total in the form): Code: <form name="submitrunnertime" action="http://......reflect.php" onsubmit="return valResultsForm();" method="post"> <table> <tr><td><label for="RunnerID">Runner ID</label></td> <td><input type="text" name="RunnerID" size="5" maxlength="5" onBlur="valRange(RunnerID, 1, 99999, 'RunnerID_bk');" /> </td><td id="RunnerID_bk"><span></span></td></tr> <tr><td><label for="">Date (YYYY-MM-DD)</label></td> <td><input type="text" name="Date" size="10" maxlength="10" onBlur="valExpression(Date, '^(19[0-9{2}|20[01][0-9])\-(0[1-9]|1[012])\-([012][0-9]|3[01])$', 'Date_bk', 'please use indicated format');" /> </td><td id="Date_bk"><span></span></td></tr> etc. etc. </table> <input type="submit" name="submitrunnertime" value="submit"> </form> I've managed to get each individual field to validate as the form is filled in. Now, if I fill valResultsForm.js with a simple line return false; then the form refuses to submit as it should do, but if I try and re-run the validation of each field so that the form will only submit if all fields have been filled in correctly, even if I force valResultsForm to return a false result, the form still submits. I just can't figure out why it is doing this and it's driving me around the bend. valResultsForm looks like: Code: function valResultsForm() { var res1 = valRange(RunnerID, 1, 99999, 'RunnerID_bk'); var res2 = valExpression(Date, '^(19[0-9{2}|20[01][0-9])\-(0[1-9]|1[012])\-([012][0-9]|3[01])$', 'Date_bk', 'please use indicated format'); if (res1 == true && res2 == true) { return true; } else { return false; } } Any hints or advice that anyone could give me would be hugely appreciated. Thank you, Andrew 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; } }); How can I go about making it so JavaScript will not let a form submit unless a number entered into a field matches a pre-specified number? A guess.. Code: function validateForm() { if (document.forms["form"]["number"].value=="123") { submit} else {alert ("Cant submit because the number doesn't match."); return false; } } Hello I've been struggling trying to get a small order form to work the way I want it to. Here is a link to the live page: http://www.watphotos.com/introductio...otography.html And here is the code in question: Code: <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ var initial = 0 var total = 0; var services = 0; function addServices() { initial = 150 total = initial services = 0; $("input:checked").each(function(){ value = $(this).attr("value"); services += parseInt(value); }); } $(function() { addServices(); total += services; $("form").before('<p class="price"></p>') $("p.price").text("Total Price: US$" + total); }); $("input:radio, input:checkbox").click(function () { addServices(); total += services $("p.price").text("Total Price: US$" + total); }); }); </script> I have two questions... Question 1 How can I make this piece of script act a little smarter. Look at the order form, I'm catering for up to 4 people and providing lunch for them. If they select 3 people and the spaghetti bol for lunch, it's only adding $10 where it should be adding $30. Obviously this is simple multiplication but since the values in my form are prices it makes it a little tricky. I'm guessing an onselect on the first part of the form which changes the pricing of the other items would be the way to go, but how do I do this? Question 2 The "Total Price" is placed before the <form> tag by the script. This is ok but it's not where I want it. How can I position this text elsewhere in the document? Thanks in advance! I'm using the jquery plugin found here. I love the look but I have a form that uses functions like this: Code: function cascadeCountry(value) { if (document.getElementById("srchlookstate_province") != null) { http.open('get', 'cascade_search.php?a=country&v=' + value ); document.getElementById('srchlookstate_province').innerHTML=" "+loadingTag; http.onreadystatechange = handleResponse; http.send(null); } } So, when you select a country and it retrieves the state/province text input, the jquery css is not applied to it. Is there something I need to add to the code above or to the jquery initialization code he Code: $(function() { $("form.jqtransform").jqTransform(); }); 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); } } } Hi, I have a working contact form with 3 of the fields requiring validation and they work well. I have added extra fields to the form (StatusClass, Project, CameFrom). These 3 fields return fine but I need to validated them. My problem is that the new fields don't show in the behaviours/validate panel even though they are within the form tag. Can anyone give me any help and advice as to how to accomplish this? Many thanks Code below.... Code: <script type="text/JavaScript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } //--> </script > Code: <form action="contact_us.asp" method="post" name="contact" target="_parent" class="contentText" id="contact" onsubmit="MM_validateForm('FullName','','R','Telephone','','RisNum','Email','','RisEmail');return document.MM_returnValue"> <table width="100%" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="54%" class="subHeader">Full Name* </td> <td width="46%" class="subHeader"><input name="FullName" type="text" id="FullName" /></td> </tr> <tr> <td class="subHeader">Company Name </td> <td class="subHeader"><input name="CompanyName" type="text" id="CompanyName" /></td> </tr> <tr> <td class="subHeader">Address</td> <td class="subHeader"><input name="Address1" type="text" id="Address1" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address2" type="text" id="Address2" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address3" type="text" id="Address3" /></td> </tr> <tr> <td class="subHeader">Postcode</td> <td class="subHeader"><input name="Postcode" type="text" id="Postcode" /></td> </tr> <tr> <td class="subHeader">Telephone Number* </td> <td class="subHeader"><input name="Telephone" type="text" id="Telephone" /></td> </tr> <tr> <td class="subHeader">Mobile Number </td> <td class="subHeader"><input name="Mobile" type="text" id="Mobile" /></td> </tr> <tr> <td height="25" class="subHeader">Email Address* </td> <td class="subHeader"><input name="Email" type="text" id="Email" /></td> </tr> <tr> <td height="30" class="subHeader">Status*</td> <td class="subHeader"><select name="StatusClass" id="StatusClass"> <option selected="selected">Please Choose</option> <option>Architect</option> <option>Interior Designer</option> <option>Private Client</option> <option>Student</option> <option>Trade Enquiry</option> </select> </td> </tr> <tr> <td height="23" class="subHeader">Project*</td> <td class="subHeader"><select name="Project" size="1" id="Project"> <option selected="selected">Please Choose</option> <option>Planning Stages</option> <option>New Build</option> <option>Refurbishment</option> <option>Barn Conversion</option> <option>No project - information only</option> </select> </td> </tr> <tr> <td height="37" class="subHeader">How did you hear about us?*</td> <td class="subHeader"><select name="CameFrom" size="1" id="CameFrom"> <option selected="selected">Please Choose</option> <option>Web Search</option> <option>Grand Designs</option> <option>Living Etc</option> <option>Home Building & Renovation</option> <option>Architect</option> <option>Friend/Family</option> <option>Magazine/Editorial</option> <option>Newspaper Article</option> <option>Trade Show/Exhibition</option> <option>Other</option> </select></td> </tr> <tr> <td height="24" class="subHeader">Brochure Request </td> <td class="subHeader"><input name="Brochure" type="checkbox" id="Brochure" value="checkbox" /></td> </tr> <tr> <td class="subHeader">Message</td> <td class="subHeader"><span class="style4"> <textarea name="Message" id="Message"></textarea> </span></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Submit" type="submit" value="Submit" /></td> </tr> <tr> <td colspan="2" class="subHeader"><em>* Required fields</em></td> </tr> </table> </form> I've set up a mock registration form page so I can learn a bit about javascript's form validation. (newbie) I want to try to attempt to style the border of a form field green when the user enters the correct info into the form text field and red on all other fields if the user doesnt enter any info into them. When i test it, enter the right info into the username field, leave the others blank, and hit the submit button it styles the username field green ok but it doesnt make the next fields (password and so on) red. Could someone please explain what I am doing wrong? here is my code so far... Note: just for testing purposes I've put return false on everything so it displays a message when everythings ok. Code: .... <script type="text/javascript"> window.onload = function() { document.forms[0].username.focus(); } function validate(form) { var form = document.getElementById("reg"); var e = document.getElementById("error"); e.style.background = "red"; for(var i = 0; i < form.elements.length; i++) { var el = form.elements[i]; if(el.type == "text" || el.type == "password") { if(el.value == "") { e.innerHTML = "Please fill in all fields!"; el.style.border = "1px solid red"; el.focus(); return false; } else { el.style.border = "1px solid green"; return false; } } } var un = form.username; un.value = un.value.replace(/^\s+|\s+$/g,""); if((un.value.length < 3)|| (/[^a-z0-9\_]/gi.test(un.value))) { e.innerHTML = "Only letters,numbers and the underscore are allowed (no spaces) - 3-16 characters"; un.focus(); return false; } var pw = form.password; pw.value = pw.value.replace(/^\s+|\s+$/g,""); if((pw.value.length < 3) || (/[^a-z0-9]/gi.test(pw.value))) { e.innerHTML = "Only letters and numbers are allowed (no spaces) - 3-16 characters"; pw.focus(); return false; } e.innerHTML = "You filled in all the fields, well done!"; e.style.background = "green"; return false; } </script> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Cool Website</h1> </div> <div id="content"> <div class="padding"> <h2>Registration</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc vitae purus. Aenean viverra malesuada libero. Fusce ac quam. Donec neque. Nunc venenatis enim nec quam. Cras faucibus, justo vel accumsan aliquam, tellus dui fringilla quam, in condimentum augue lorem non tellus. Pellentesque id arcu non sem placerat iaculis. Curabitur posuere, pede vitae lacinia accumsan, enim nibh elementum orci, ut volutpat eros sapien nec sapien. Suspendisse neque arcu, ultrices commodo, pellentesque sit amet, ultricies ut, ipsum. Mauris et eros eget erat dapibus mollis. Mauris laoreet posuere odio. Nam ipsum ligula, ullamcorper eu, fringilla at, lacinia ut, augue. Nullam nunc.</p> <form id="reg" action="#" method="post" onsubmit="return validate(this)"> <div id="error"></div> <div><label for="username">Username</label></div> <div><input type="text" name="username" id="username" size="30" maxlength="16" /></div> <div><label for="password">Password</label></div> <div><input type="password" name="password" id="password" size="30" maxlength="16" /></div> <div><label for="c_password">Confirm Password</label></div> <div><input type="password" name="c_password" id="c_password" size="30" maxlength="16" /></div> <div><label for="email">Email address</label></div> <div><input type="text" name="email" id="email" size="30" maxlength="200" /></div> <div><label for="c_email">Confirm Email address</label></div> <div><input type="text" name="c_email" id="c_email" size="30" maxlength="200" /></div> <div><label for="firstname">First name</label></div> <div><input type="text" name="firstname" id="firstname" size="30" maxlength="100" /></div> <div><label for="surname">Surname</label></div> <div><input type="text" name="surname" id="surname" size="30" maxlength="100" /></div> <div><label for="gender">Gender</label></div> <div> <div><input type="radio" name="gender" id="gender" value="m" checked="checked" />Male</div> <div><input type="radio" name="gender" value="f" />Female</div> </div> <div><input type="submit" value="Register" name="submit" /></div> </form> </div> </div> <div id="footer"> <p>Copyright © 2009 My Cool Website</p> </div> </div> </body> </html> 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> Hello all, I have a multistep jquery form that validates user input and then should send me an email. Problem is, right now, I can only get it to validate the first page, then it sends the email before the rest of the pages are viewed. I'm just trying to delay the submission of the form until the "submit_fourth" button is pressed. I've got $25 via paypal for the one who sticks with this one for long enough to come up with a workable solution. Here is my code... I know it's a lot, but I wasn't sure how much would be helpful. HTML code is in the second post in this thread (it was just too much to fit in one go). Cheers! -Dave The Javascript: Code: $(function validateForm(){ //original field values var field_values = { //id : value 'name' : 'your name', 'email' : 'email', 'phone' : '(555) 123-4567', 'other' : 'other', 'detail' : 'project overview' }; //inputfocus $('input#name').inputfocus({ value: field_values['name'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('input#phone').inputfocus({ value: field_values['phone'] }); $('input#other').inputfocus({ value: field_values['other'] }); $('input#detail').inputfocus({ value: field_values['detail'] }); //reset progress bar $('#progress').css('width','0'); $('#progress_text').html('0% Complete'); //first_step $('form').submit(function(){ }); $('#submit_first').click(function(){ //remove classes $('#first_step input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields1 = $('#first_step input[type=text]'); var error = 0; fields1.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#first_step').slideUp(); $('#second_step').slideDown(); } else return false; }); $('#back_second').click(function(){ //update progress bar $('#progress_text').html('0% Complete'); $('#progress').css('width','0px'); //slide steps $('#second_step').slideUp(); $('#first_step').slideDown(); }); $('#submit_second').click(function(){ //remove classes $('#second_step input').removeClass('error').removeClass('valid'); var fields2 = $('#second_step input[textarea]'); var error = 0; fields2.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#second_step').slideUp(); $('#third_step').slideDown(); } else return false; }); $('#back_third').click(function(){ //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#third_step').slideUp(); $('#second_step').slideDown(); }); $('#submit_third').click(function(){ //update progress bar $('#progress_text').html('75% Complete'); $('#progress').css('width','255px'); //prepare the fourth step var fields3 = new Array( $('#time').val(), $('#budget').val() ); var fields2half = new Array( $('#detail').val() ); var fields2 = new Array( $('#other').val(), $('#pages').val() ); var fields1 = new Array( $('#name').val(), $('#email').val(), $('#phone').val(), $('#contact').val(), $('#url').val() ); var tr = $('#fourth_step tr'); tr.each(function(){ //alert( fields[$(this).index()] ) $(this).children('.1 td:nth-child(2)').html(fields1[$(this).index()]); $(this).children('.2 td:nth-child(2)').html(fields2[$(this).index()]); $(this).children('.2half td:nth-child(2)').html(fields2half[$(this).index()]); $(this).children('.3 td:nth-child(2)').html(fields3[$(this).index()]); }); //slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown(); }); $('#back_fourth').click(function(){ //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#fourth_step').slideUp(); $('#third_step').slideDown(); }); $('#submit_fourth').click(function(){ //send information to server //update progress bar $('#progress_text').html('100% Complete'); $('#progress').css('width','339px'); //slide steps $('#fifth_step').slideUp(); $('#fourth_step').slideDown(); if(error <= 0) { return true } else{ return false } }); }); Hi. I am new here. I wanted help for a JavaScript code. You might think I'm lazy for not writing it myself, but the truth is I am not a JavaScript coder. I just have a really simple website and I am trying to do something for which I know JS is required but I don't know how to do it. I've also searched around but couldn't find the appropriate code. I created a submission form for users when they log in to my website they can submit their info . when they fill the form and click on submit button is not sending the info to my email .............................please help here is my my codes please take a look at it Thanks 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"> <meta name="verify-v1" content="N1J6LLa/OdGf52xzkbegP/YFAD+RaeKa9FQ2/8UJfKo="> <title>southernfiremag.co.za</title> <link href="southernfiremag.co.za_files/webstyle.css" rel="stylesheet" type="text/css"> <link href="southernfiremag.co.za_files/balloontip.css" rel="stylesheet" type="text/css"> <script src="southernfiremag.co.za_files/balloontip.js" type="text/javascript"></script><style media="screen" type="text/css">#FLheader {visibility:hidden}</style><style media="screen" type="text/css">#subFlash {visibility:hidden}</style><style media="screen" type="text/css"> #footer {visibility:hidden}.style1 {color: #FFFFFF} body { background-color: #000000; } </style></head><body class="sIFR-active"><div id="dhtmltooltip"></div> <script src="southernfiremag.co.za_files/gen_validatorv2.js" type="text/javascript"></script> <div id="container"> <script type="text/javascript"> var flashvars = { dater:'', }; var params = {}; params.menu = "false"; params.wmode = "transparent"; params.bgcolor = "#1A1A1A"; var attributes = {}; swfobject.embedSWF("/header.swf", "FLheader", "977", "145", "8.0.0", false, flashvars, params, attributes); </script> <div id="maincontent"> <script type="text/javascript"> var flashvars = { }; var params = {}; params.menu = "false"; params.wmode = "transparent"; params.bgcolor = "#1A1A1A"; var attributes = {}; swfobject.embedSWF("/subHeader.swf", "subFlash", "963", "167", "8.0.0", false, flashvars, params, attributes); </script> <div class="textArea"> <div id="crumbsBar"><b><a href="http://www.southernfiremag.co.za/">SOUTHERN FIRE MAG</a></b> >> <a href="http://www.southernfiremag.co.za/submissions/model_submission.php">MODEL SUBMISSION </a> >> Submit to modelsubmission@southernfiremag.co.za</div> <div id="adPanel"> <img src="southernfiremag.co.za_files/become_Southern Fire Girl.png" border="0" height="258" width="292"><br> <!-- <a href="/join/"><img src="/images/membershipPrice.jpg" alt="" width="186" height="117" border="0" /></a><br />--> <img src="southernfiremag.co.za_files/index_20.jpg" alt="" height="258" width="292"><br> <img src="southernfiremag.co.za_files/ban_secure.jpg" alt="" height="120" width="186"><br> <img src="southernfiremag.co.za_files/ban_updates.jpg" alt="" height="120" width="186"><br> <br> <br class="clear"> </div> <div id="mainPanel"> <h1 style="" class="sIFR-replaced"> </h1> <h2 class="sIFR-replaced" style="width: 460px;"> </h2> </div> <br class="clearLeft"> <div style="width: 400px; float: left;"> <p><span class="style1">Fill out this form with your pics. Be sure to include head-shots, commercial fashion, glamour/swim and beauty. </span></p> <div> <form action="index.htm" method="post" enctype="multipart/form-data" name="SOUTHERN FIRE MAG" id="SOUTHERN FIRE MAG"> <table class="tableBK" border="0" cellpadding="3" cellspacing="1" width="400px"> <!--DWLayoutTable--> <tbody><tr> <td colspan="2" height="35"></td> </tr> <tr> <td width="141" height="24"><b class="formfont"><span style="color: red">*</span><span class="style1"> Name: </span></b></td> <td width="242"><input name="name" id="name" size="25" type="text"> </td> </tr> <tr> <td height="24"><b><span style="color: red">*</span><span class="style1"> Email:</span></b></td> <td><input name="email" id="email" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Address:</span></td> <td><input name="address" id="address" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">City:</span></td> <td><input name="city" id="city" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">State:</span></td> <td><input name="state" id="state" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Zip:</span></td> <td><input name="zip" id="zip" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Phone:</span></td> <td><input name="phone" id="phone" size="25" type="text"> </td> </tr> <tr> <td height="29"> </td> <td> </td> </tr> <tr> <td height="24"><span style="color: red">*</span><span class="style1"> Stage Name:</span></td> <td><input name="alias" id="alias" size="25" type="text"> </td> </tr> <tr> <td height="24"><span class="style1">Age:</span></td> <td class="tdGrey2"><input name="age" id="age" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Ethnicity:</span></td> <td class="tdGrey2"><input name="ethnicity" id="ethnicity" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Height:</span></td> <td class="tdGrey2"><input name="height" id="height" size="25" type="text"></td> </tr> <tr> <td height="25"><span class="style1">Weight:</span></td> <td class="tdGrey2"><select name="weight"> <option selected="selected" value="85-99">85-99</option> <option value="100-110">100-110</option> <option value="111-115">111-115</option> <option value="116-125">116-125</option> <option value="126-135">126-135</option> <option value="136-145">136-145</option> <option value="146-155">146-155</option> <option value="156-165">156-165</option> <option value="Other">Other</option> </select></td> </tr> <tr> <td height="24"><span class="style1">Bust:</span></td> <td class="tdGrey2"><input name="bust" id="bust" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Waist:</span></td> <td class="tdGrey2"><input name="waist" id="waist" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Hip:</span></td> <td class="tdGrey2"><input name="hip" id="hip" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Shoe:</span></td> <td class="tdGrey2"><input name="shoe" id="shoe" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Dress:</span></td> <td class="tdGrey2"><input name="dress" id="dress" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Agency:</span></td> <td class="tdGrey2"><input name="agency" id="agency" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Personal Website:</span></td> <td class="tdGrey2"><input name="website" id="website" size="25" type="text"></td> </tr> <tr> <td height="29"> </td> <td> </td> </tr> <tr> <td height="45" colspan="2"><span class="style1">We have several different photographers that we work with in the following Country. Please select which Country you are willing to meet with our photographers if selected for a test shoot? </span></td> </tr> <tr> <td height="25"><span class="style1">Country:</span></td> <td><!--<input name="location" type="text" id="location" size="25" value="" > --> <select name="location"> <option selected="selected" value="SOUTH AFRCA">SOUTH AFRICA</option> <option value="USA">USA</option> <option value="DRC CONGO">DRC CONGO</option> <option value="ANGOLA">ANGOLA</option> <option value="MOZABIQUE">MOZABIQUE</option> <option value="MILAN">MILAN</option> <option value="OTHERS">OTHERS</option> </select></td> </tr> <tr> <td colspan="2" height="2"></td> </tr> <tr> <td height="32" colspan="2"><span style="color: red;">Image upload is required.</span> <span class="style1">Please upload 1 or up to 4 images below. Each image size must be below 1MB</span></td> </tr> <tr> <td colspan="2" height="2"></td> </tr> <tr> <td height="27"><span style="color: red">*</span><span class="style1"> Image 1</span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label> </td> </tr> <tr> <td height="27" valign="top"><span class="style1">Image 2 </span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label></td> </tr> <tr> <td height="27" valign="top"><span class="style1">Image 3 </span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label></td> </tr> <tr> <td height="27" valign="top"><span class="style1">Image 4 </span></td> <td><label><span class="td1"> <input name="fileatt[]" type="file"> </span></label></td> </tr> <tr> <td height="29"> </td> <td> </td> </tr> <tr> <td height="24"><span class="style1">Myspace<b>:</b></span></td> <td><input name="myspace" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">ModelMayhem<b>:</b></span></td> <td><input name="mayhem" size="25" type="text"></td> </tr> <tr> <td height="24"><span class="style1">Facebook<b>:</b></span></td> <td><input name="facebook" size="25" type="text"></td> </tr> <tr> <td height="8" colspan="2"> <hr> </td> </tr> <tr> <td height="24"><span class="style1">Twitter<b>:</b></span></td> <td><input name="twitter" size="25" type="text"></td> </tr> <tr> <td height="32" colspan="2"> <span class="style1">Have a twitter account? If so, let us know your account and we'll post your tweets here. </span></td> </tr> <tr> <td height="8"></td> <td></td> </tr> <tr> <td height="87" valign="top"><span class="style1">TV</span></td> <td> <textarea name="tv" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Film</span></td> <td> <textarea name="film" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Commercial</span></td> <td> <textarea name="commercial" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Advertising</span></td> <td> <textarea name="advertising" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Editorial</span></td> <td> <textarea name="editorial" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Music Video</span></td> <td> <textarea name="music" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Web</span></td> <td> <textarea name="web" cols="45" rows="6"></textarea> </td> </tr> <tr> <td height="26" valign="top"><span class="style1">Tattoos?</span></td> <td> <input name="tyn" value="yes" type="radio"> Yes <input name="tyn" value="no" checked="checked" type="radio"> No<br> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Give more details about your tattoos...</span></td> <td> <textarea name="tattoos" cols="45" rows="6" id="tattoos"></textarea> </td> </tr> <tr> <td height="87" valign="top"><span class="style1">Why are you the right girl for SOUTHERN FIRE...</span></td> <td><textarea name="description" cols="45" rows="6" id="description"></textarea> </td> </tr> <tr> <td height="24" valign="top"><span class="style1">3 + 4 =?</span></td> <td> <!-- <img src="/submissions/random_code/code.php" alt="" /><br /> --> <input name="code" type="text"> </td> </tr> <tr> <td colspan="2" class="tablebar" height="2"></td> </tr> <tr> <td height="41" colspan="2" align="center" class="tdGrey2"> <input name="action" id="action" value="sendform" type="hidden"> <input name="Submit" src="southernfiremag.co.za_files/confrim.gif" value="SUBMIT" type="image"> </td> </tr> <tr> <td colspan="2" class="tdGrey" height="5"></td> </tr> </tbody></table> </form> <script language="JavaScript" type="text/javascript">//You should create the validator only after the definition of the HTML form var frmvalidator = new Validator("SOUTHERN FIRE MAG"); frmvalidator.addValidation("email","maxlen=50"); frmvalidator.addValidation("email","req","Please enter your email address"); frmvalidator.addValidation("email","email"); frmvalidator.addValidation("name","req","Please enter your name"); frmvalidator.addValidation("alias","req","Please enter your alias"); </script> </div> </div> <div style="width: 250px; float: left; text-align: left; margin-left: 10px;"> <!-- right side - inner content --> <!-- <img src="/images/extra/041410/bmd1.jpg" alt="" /><br /><br /> <img src="/images/extra/041410/bmd2.jpg" alt="" /><br /><br /> <img src="/images/extra/041410/bmd3.jpg" alt="" /><br /> --> </div> <br class="clear"> </div> <br class="clear"> </div> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script><script src="southernfiremag.co.za_files/ga.js" type="text/javascript"></script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-589703-16"); pageTracker._trackPageview(); } catch(err) {} </script> </body></html> I have the below code to validate and send my form. It sends the email fine, but I receive the error message at the bottom of the page instead of the success message. Any help on why it is doing this would be great. This is my first form validation script. Here is the page live: Website here is the javascript: Code: $(document).ready(function() { $('form #response').hide(); $('#submitbtn').click(function(e) { e.preventDefault(); var valid = ''; var required = ' is required.'; var name = $('form #name').val(); var phone = $('form #phone').val(); var email = $('form #email').val(); var details = $('form #details').val(); var honeypot = $('form #honeypot').val(); var humancheck = $('form #humancheck').val(); if (!name.match(/^[A-Za-z ]{3,20}$/)) { valid = '<p>- Your name' + required +'</p>'; } if (!phone.match(/^([1]-)?[0-9]{3}-?[0-9]{3}-?[0-9]{4}$/i)) { valid += '<p>- A valid phone number' + required +'</p>'; } if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) { valid += '<p>- A valid email address' + required +'</p>'; } if (honeypot != 'http://') { valid += '<p>Spambots are not allowed.</p>'; } if (humancheck != '') { valid += '<p>A human user' + required + '</p>'; } if (valid != '') { $('form #response').removeClass().addClass('error') .html('<strong>Please correct the errors below:</strong>' + valid).fadeIn('fast'); } else { $('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast'); var formData = $('form').serialize(); submitForm(formData); } }); }); function submitForm(formData) { $.ajax({ type: 'POST', url: 'bookings.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success') .html(data.msg).fadeIn('fast'); if ($('form #response').hasClass('success')) { setTimeout("$('form #response').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('form #response').removeClass().addClass('error') .html('<strong>There was an error. Please use the above information and contact us directly.</strong>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status) { $('form')[0].reset(); } }); }; PHP Code: PHP Code: <?php sleep(4); $name = trim(stripslashes(htmlspecialchars($_POST['name']))); $phone = trim(stripslashes(htmlspecialchars($_POST['phone']))); $email = trim(stripslashes(htmlspecialchars($_POST['email']))); $details = trim(stripslashes(htmlspecialchars($_POST['details']))); $humancheck = $_POST['humancheck']; $honeypot = $_POST['honeypot']; if ($honeypot == 'http://' && empty($humancheck)) { //Validate data and return success or error message $error_message = ''; $name_check_exp = "/^[A-Za-z ]{3,20}$/"; $phone_check_exp = "/^([1]-)?[0-9]{3}-?[0-9]{3}-?[0-9]{4}$/i"; $email_check_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/"; if (!preg_match($name_check_exp, $name)) { $error_message .= "<p>Your name is required.</p>"; } if (!preg_match($phone_check_exp, $phone)) { $error_message .= "<p>A valid phone number is required.</p>"; } if (!preg_match($email_check_exp, $email)) { $error_message .= "<p>A valid email address is required.</p>"; } if (!empty($error_message)) { $return['error'] = true; $return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message; echo json_encode($return); exit(); } else { //send to an email $emailSubject = 'Bookings Form'; $webMaster = 'some.email@gmail.com'; $body=" <br><hr><br> Name: $name <br> Phone: $phone <br> Email: $email <br> Details: $details "; $headers = "From: $email\r\n"; $headers .= "Content-type: text/html\r\n"; //send email and return to user if(mail($webMaster, $emailSubject, $body, $headers)) { $return['error'] = false; $return['msg'] = "<p>Message sent successfully. Thank you for your intrest " .$name .".</p>"; echo json_encode($return); } else { $return['error'] = true; $return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>"; echo json_encode($return); } } } ?> Ok, I am reasonably new to javascript, and I have been trying to code some really basic client-side form validation. The validation part is working, but for some reason the form won't submit if no errors are found. I have tried all different variations of the submit syntax. i.e. document.login_form.submit();. But settled with the one on W3Schools even though it still didn't work. I would really appreciate any advise. Here is my code: Code: <head> <title>Project Rival - Authentication</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> function verify() { var themessage = "Please enter your"; if (document.login_form.user.value=="") { themessage = themessage + " username"; } if (document.login_form.user.value=="" && document.login_form.pass.value=="") { themessage = themessage + " and"; } if (document.login_form.pass.value=="") { themessage = themessage + " password"; } //alert if fields are empty and cancel form submit if (document.login_form.user.value!="" && document.login_form.pass.value!="") { document.getElementById("login_form").submit(); return true; } else { document.getElementById("error").innerHTML = themessage; return false; } } </script> </head> <body> <div id="container"> <div id="login_box_top"> </div> <div id="logo"><img src="images/projectrival.jpg" width="150"/></div> <div id="error"></div> <div id="login"> <form action="login.php" method="post" name="login_form" id="login_form"> <input name="user" class="input" id="user" type="text" size="30" maxlength="30" /><br /><br /> <input name="pass" class="input" id="pass" type="password" size="30" maxlength="30" /><br /><br /> <input name="submit" id="submit" type="button" value="Login" onclick="verify()" /> </form> </div> <div id="login_box_bottom"> </div> <div id="copy"><p>© Martin Day 2011 </div> </div> </body> </html> Many Thanks Hi and hope someone can help. I have a form with various input fields and, on submission, I'd like some validation done and if that's OK, for it to load another page in the parent directory. Trouble is I end up with Error 404 when I test it, the page actually exists but when I look at the URL within the Error 404 page it looks like this... Code: http://localhost/my_sites/webmaestro/assignments/Lesson06/pages/register()?First_Name=&Initials=&Last_Name=&Address_Line_1=&Address_Line_2=&City=&County=&Post_Code=&Email=&submit=Register The URL with the form on it is... Code: http://localhost/my_sites/webmaestro/assignments/Lesson06/pages/wm6ex1_register.html and the page I'm trying to call is... Code: http://localhost/my_sites/webmaestro/assignments/Lesson06/wm6ex1_home.html Is the problem to do with the fact that the form is actually trying to pass all those variables from the input fields? My form looks like this... Code: <form method="get" name="register" action="register()" onreset="return confirm('This will remove all your entries so far.\nIs that O.K?')" > Various input fields here. <input type="reset" name="reset" value="Reset" /> <input type="submit" name="submit" value="Register" /> </form> My function currently has no validation and simply looks like this... Code: function register() { window.open("../wm6ex1_home.html", "_self") } My thanks R I have this form he When a user enters a value in the quantity field that is NaN then a alert messages comes up for the user, also when the NAN is entered the value is submitted on the form. If the user enters a number then then that number is submitted on the form. What I want to do is when the user enters NAN the alert keeps coming up and the value is not submitted on the form, but if they enter no value or a number those values will be submitted on the form. Code: <script> function getCost(tool,price){ var tags = document.getElementsByName(tool); var str = tags[0].value; str = str.trim(); if (str == "") return 0; var quanity = Number(str); if(isNaN(quanity)) { alert("Please enter a valid number for the " + tool); quanity = 0; return false; } } function validateInput(){ val = getCost("Saw",12); if (val == "NaN") return false; val = getCost("Hoe",18); if (val == "NaN") return false; val = getCost("Tree Trimmer",22); if (val == "NaN") return false; } </script> <form action="http://crm.abc.com/formtest.php" method="post" onsubmit="return validateInput();"> <p> <label> Buyer's Name: <input type="text" name="name" size="30"/> </label> <label> Street Address: <input type="text" name="street" size="30"/> </label> <label> City, State, Zip: <input type="text" name="city" Size="30"/> </label> </p> <table> <tr> <th> Tool Name </th> <th> Price </th> <th> Quantiy </th> </tr> <tr> <td> Saw </td> <td> $12.00</td> <td> <input type= "text" name="Saw" size="2" /> </td> </tr> <tr> <td> Hoe </td> <td> $18.00 </td> <td> <input type="text" name="Hoe" size="2" /> </td> </tr> <tr> <td> Tree Trimmer </td> <td> $22.00 </td> <td> <input type="text" name="Tree Trimmer" size="2" /> </td> </tr> </table> <h2> Payment Method </h2> <label> Visa <input type="radio" name="payment" id="payment_visa" value="visa" checked="checked"/> </label> <br /> <label> Mastercard <input type="radio" name="payment" id="payment_mastercard" value="mastercard"/> </label> <br /> <label> American Express <input type="radio" name="payment" id="payment_american_express" value="american express"/> </label> <br /> <input type="submit" value="Submit" /> </form> All my parameters will not work after my first form submission unless I refresh my page. Is there a way to refresh the page after the page loads without a continuous loop of refreshes?
I am trying to submit my form and receive a success message that go's away. My form validation is working fine and I receive the email, but the echo back to json is giving my error message instead of my success message. This is my first try doing this and am brand new to javascript. If anyone could please help me figure out what is wrong or tell me how to rewrite it, I would be much obliged. Code: function submitForm(formData) { $.ajax({ type: 'POST', url: 'bookings.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success') .html(data.msg).fadeIn('fast'); if ($('form #response').hasClass('success')) { setTimeout("$('form #response').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('form #response').removeClass().addClass('error') .html('<strong>There was an error. Please use the above information and contact us directly.</strong>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status) { $('form')[0].reset(); } }); }; Hello, I'm using simple form validation, found online, to check certain fields before submitting. The problem is that, although the script detects the error/missing field/wrong syntax and pops up the corresponding alert, after the user presses OK in the alert box the script continues and sends the form - which of course is not valid. HTML PART: Code: <input name="Submit" type="submit" class="textfield" value="Register" onclick="checkitems();"> JAVASCRIPT PART: Code: function checkitems() { valid = true; if ( document.registration.Onoma.value == "" ) { alert ( "Please enter your name." ); return false; } if ( document.registration.HlekDieuthinsi.value == "" ) { alert ( "Please enter your email." ); return false; } var e=document.registration.HlekDieuthinsi.value var emailFilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i if (!(emailFilter.test(e))) { alert ( "The email address you entered is not valid." ); return false; } return valid; } Hi I have an insert form.....to insrt data to DB. if user typed in something, BUT clicked on an url in navigation menu TO GO to an OTHER Page...I would be able to give an alert to user-"please submit the form" some thing that way.....Is it possible to do?? pls suggest me some example... TIA Hi All, I have created my second Form to File Web Form thanks to some help from other members. Looks great. I am still new to HTML and Javascript, but basically I took my First Web Form coding (with the Java Script) and manipulated it so that it suited my needs for my 2nd Form (both are very close to being the same). For some reason, I can't get my Java Script validation to take effect. I was wondering if some one could try to pin point why it isn't functioning properly? Again it could be the most obvious thing, but please bear with me as I learn. Just for a little more clarity, I am going to list the things that I have changed to possibly make it easier to pin point: Added Fields: Department, SteetAddress, CityState Deleted: State/Research Accounts, Vendor Checkbox Modified: "Type" which is a radio button that I have changed the choices of. I beleive that's it...I will post my Java Script here and attach my Index File. Thank you in advance!! Code: /******************************************************************************** * * FORM VALIDATION * ********************************************************************************/ // get the value of a radio button group: function getRBValue(grp) { if ( grp.length == null ) return grp.checked ? grp.value : null; for ( var g = 0; g < grp.length; ++g ) { if ( grp[g].checked ) return grp[g].value; } return null; } // trim a string function trim(fld) { var val = fld.value.replace(/^\s+/,"").replace(/\s+%/,"").toUpperCase(); fld.value = val; return val; } var echk = /^([a-z][\w\-\'\.]*)+\@([a-z][\w\-\'\.]+\.)+[a-z]{2,6}$/i function emailCheck( fld ) { var email = trim( fld ); fld.value = email; return echk.test(email); } var digonly = /[^\d]/g function formatPhone( fld ) { var ph = fld.value.replace( digonly, "" ); if ( ph.length != 10 ) return; fld.value = "(" + ph.substring(0,3) + ") " + ph.substring(3,6) + "-" + ph.substring(6); } var phchk = /^\(\d\d\d\) \d\d\d\-\d\d\d\d$/ function phoneCheck( fld ) { return phchk.test(fld.value); } function validateForm( frm ) { var oops = ""; if ( trim( frm.elements["Username."] ).length < 5 ) oops += "You must enter your first and last name\n"; if ( ! emailCheck( frm.elements["Email."] ) ) oops += "That does not appear to be a valid email address\n"; if ( trim( frm.elements["Department."] ).length < 3) oops += "You must enter your department name\n"; if ( ! phoneCheck( frm.elements["Phone."] ) ) oops += "That is not a valid 10-digit phone number\n"; if ( trim( frm.elements["ShipToBuildingRoom."] ).length < 5 ) oops += "You must enter your building and room information\n"; if ( trim( frm.elements["StreetAddress."] ).length < 5 ) oops += "You must enter your street address information\n"; if ( trim( frm.elements["CityZip."] ).length < 5 ) oops += "You must enter your city and zip code information\n"; apptype = getRBValue( frm.elements["Type."] ); if ( apptype == null ) oops += "You must check one class\n"; var app = getRBValue( frm.RequireApprovalYesNo ); if ( app == null ) oops += "You must specify whether or not approval is required.\n"; if ( app == "Yes" ) { if ( trim( frm.Approver ).length < 5 ) oops += "You must enter the name of the approver\n"; if ( ! emailCheck( frm.ApprovalEmail ) ) oops += "The approval email is not a valid email address\n"; } } function showapp(yesno) { document.getElementById("APP1").style.display = document.getElementById("APP2").style.display = document.getElementById("APP3").style.display = yesno ? "" : "none"; } </SCRIPT> |