JavaScript - Js Form Validation Using Functions
Hi guys,
I need some help here.. I have created a simple JS and HTML NAME form validation and checked box as shown (If anyone can help me about the check box a better and easy way to code would be great). I would like to use the functions that I have created - can anyone tell me HOW I can use them please? I tried to use like this.. Code: var name = document.getElementById('name').value; if(name(!notEmpty && !isAlphabet)) { error_mesg += "\nPlease enter your Name"; error_num++; } ..but it does not work...anyone can give me some idea? Code: .. .. <script type='text/javascript'> function formValidation(){ var error_mesg = "Following error found\n"; var error_num = 0; var name = document.getElementById('name').value; if(name==""){ error_mesg += "\nPlease enter your Name"; error_num++; } var terms = !document.getElementById('terms').checked; //Can anyone tell me what is the function of "checked" here for? if (terms){ error_mesg += "\nPlease check the terms and conditions"; error_num++; } if(error_num>0){ alert(error_mesg); elem.focus(); return false; }else{ //submit form return true; } } function notEmpty(elem, error_mesg){ if(elem.value.length == 0){ alert(error_mesg); elem.focus(); // set the focus to this input return false; } return true; } function isAlphabet(elem, error_mesg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(error_mesg); elem.focus(); return false; } } .. .. [HTML FORM] .. <form name="form" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onsubmit="return formValidation()"> <tr align="left" valign="top> <td width="20%">NAME:<font color="#CE0000" >*</font></td> <td width="80%"><input name="name" type="text" id="name" size="30" /></td> </tr> <tr><td><input type=checkbox name=terms value='yes'>I agree to terms and conditions </td></tr> .. .. <input type="hidden" name="action" value="register"/> <input name="submit" type="submit" value="Proceed" /> Similar Tutorialswhen user clicks submit first it should check to see if a name from the dropdown has been selected then it should check to make sure all radio buttons were selected. code to check if a name was selected in the drop down. Code: <script type="text/javascript"> window.onload=function(){ document.forms[0].onsubmit=function(){ return formValid(this); } } function formValid(formObj){ var sel=formObj.getElementsByTagName('select'); var len=sel.length; var msg = "You forgot to select your name" var flg=false; for(var i=0;i<len;i++){ if(sel[i].selectedIndex==0){ msg; flg=true; } } if(flg){ alert(msg); return false; }else{ return true; } } </script> <br><br> <html> code that checks to see if all radio buttons were selected. Code: function validateTest() { var focus_me = null; var msg = ""; var form = document.forms[0]; for ( var game = 1; game <= 999999; ++game ) { var rbg = form["game" + game]; if ( rbg == null ) break; // no more games if ( ! rbg[0].checked && ! rbg[1].checked ) { msg += rbg[0].value + " vs. " + rbg[1].value + "\n"; focus_me = focus_me || rbg[0]; } } if (msg != "") { var prefix = "\n WARNING: The following Games(s) were not selected:\n\n"; var suffix = "\nClick OK and select all games before clicking submit.\n\n"; alert(prefix + msg + suffix); if (focus_me) focus_me.focus(); return false; } else{ return true; } } Code: center> <INPUT TYPE=SUBMIT VALUE="submit" onClick="Validate(this.form, 'game1')"> </FORM> how can i add these two functions together so it validates both? Hello all, new here Seems like a very nice place to be apart of. I have my website www.gebcn.com. If you view source you will see all that I have done, but more importantly my problem. I have the JS code at the top there and I am unable to W3C validate my HTML because of the JS. I am using XHTML strict and would like to stay using it. The JS I have at the top is my form validation code. I am able to do any validating that I need with this "snippet" of code, I have shrank it from my library version just to use for this newsletter. Until now W3C validating was not important now for some reason it is and I am faced with this problem. I am not a Javascript guy more of a HTML/CSS guy and I can manipulate JS to suit my needs. <problem> I have tried to make this "snippet" of JS code an external file but receive multiple errors with the JS calling for the FORM NAME as it is not on the same page. The form NAME=NEWSLETTER is another problem, as W3C says I am unable to use attribute "NAME" in this location. <problem> I would like to keep the JS close to how it is now as I have a library to use this JS over and over again. Any pointers in the right direction or solutions to my problem would be greatly appreciated. Thanks! Hopefully it is not to hard huh If there is anything anyone needs, the code pasted here, or anything else please let me know. Thanks again! I would like to start off by saying I know there isn't a sure fire, 100% way to tell if javascript is enabled on a users browser. Because of this, it's a good idea to check form input using a php (or another server-side language) function. Now, let's say the user DOES have javascript enabled. I would like to check that same form input with a javascript function, instead of a php function. How would I be able to do that? If both php and javascript functions are in the same script, how does the browser know which one to run and how can I make it run the javascript function if the user has javascript enabled? 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 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 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> I have been working on a JavaScript form with validation and I cant get it to work right. The form is supposed to validate the name, E-mail, Phone number, Password and confirmation, Drop-down selection, Question reply, yes and no radios, and 3 preferences check-boxes. It is also supposed to verify that the passwords match, not allow any letters or special characters in the phone number box, and remove the default text when a user clicks on the Name, E-mail, and Question reply boxes. I've been checking over the code for almost a month now and I can't figure out why it is not working. This is my entire code. [CODE] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Contact</title> <script type="text/javascript"> /* <![CDATA[ */ function onlyDigits(objtextbox) { var exp = /[^\d]/g; objtextbox.value = objtextbox.value.replace(exp,""); } function textdisappear(txt) { if (txt.value == txt.defaultValue) { txt.value = "" } function passmatch() { if (document.forms[0].psswrd2.value != document.forms[0].psswrd1.value) { window.alert("You did not enter the same password!"); document.forms[0].psswrd1.focus(); } function validate() { var name = document.form1.Name; var email = document.form1.Email; var phone = document.form1.Telephone; var question = document.form1.selection; var reply = document.form1.questionreply var word1 = document.form1.psswrd1 var word2 = document.form1.psswrd2 var chkradio = false; var chkbox = false; if (name.value == "") { window.alert("Name please."); name.focus(); return false; } if (email.value == "") { window.alert("E-mail is blank."); email.focus(); return false; } if (email.value.indexOf("@", 0) < 0) { window.alert("Enter valid e-mail please."); email.focus(); return false; } if (email.value.indexOf(".", 0) < 0) { window.alert("Enter valid e-mail please."); email.focus(); return false; } if ((phone.value == "")) { window.alert("Telephone number please."); phone.focus(); return false; } if (word1.value == "") { window.alert("Password please."); word1.focus(); return false; } if (word2.value == "") { window.alert("Re-type password please."); word2.focus(); return false; } if (question.selectedIndex < 1) { alert("Choose question please."); question.focus(); return false; } if (reply.value == "" || reply.value == "Question reply") { window.alert("Question reply please."); reply.focus(); return false; } for (var i=0; i<2; ++i) { if (document.form1.confirmreply.checked == true) { chkradio = true; break; } if (chkradio != true) { window.alert("Yes or no please."); confirmrelpy.focus(); return false; } for (var i=0; i<3; ++i) { if (document.form1.hobby.checked == true) { chkbox = true; break; } if (chkbox != true) { window.alert("Choose preference."); hobby.focus(); return false; } return true; } /* ]]> */ </script> </head> <body> <center><h1>Contact</h1></center> <form method="post" action="mailto:someemail@somedomain.com" name="form1" onsubmit="return validate();"> <h3>Your Details</h3> <p>Name:* <input type="text" name="Name" value="Enter Name" onfocus="textdisappear(this)" ></p> <p>E-mail:* <input type="text" name="Email" value="Enter E-mail" onfocus="textdisappear(this)" ></p> <p>Phone Number:* <input type="text" name="Telephone" onkeyup="onlyDigits(this)"><br> <br /> <h3>Password and Secret Question</h3> Password:<br /> <input type="password" name="psswrd1" value="" />*<br /> Confirm:<br /> <input type="password" name="psswrd2" value="" onblur="passmatch()" />*<br /> <p>Choose a question:*<br /> <select type="text" value="" name="selection"> <option> </option> <option>Where was your elementary school?</option> <option>Who was the first person you ever kissed?</option> <option>What was your first car?</option> <option>Who is your favorite author?</option> </select><br /> reply<br /> <input type="text" name="questionreply" value="Question reply" onfocus="textdisappear(this)" />*<br /> <h3>Offers</h3> Do you want any special offers sent to you?*<br /> Yes<input type="radio" name="confirmreply" value="Yes"/>No<input type="radio" name="confirmreply" value="No" /> <h3>Which preference do you have?*</h3> <input type="checkbox" name="hobby" value="check"/>Inside Activities<br /> <input type="checkbox" name="hobby" value="check"/>Outside Activities<br /> <input type="checkbox" name="hobby" value="check"/>Both<br /> <br /> <p><input type="submit" value="Submit" name="submit" /> <input type="reset" value="Reset" name="reset"></p> </form> </body> </html> [CODE] <?php session_start(); include_once "../c-library/errorcheck.inc.php"; function viewForm($input,$errors){ //$array[] = $var; $num_days= array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21 ","22","23","24","25","26","27","28","29","30","31"); $num_months = array(1=>"Jan",2=>"Feb",3=>"Mar",4=>"Apr",5=>"May",6=>"Jun", 7=>"Jul",8=>"Aug",9=>"Sept",10=>"Oct",11=>"Nov",12=>"Dec" ); $gender = array("Male","Female"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Register</title> <script src="reload_vals.js" type="text/javascript"></script> <style media="all"> table{ table-layout:auto; width:auto;} th{ text-align:right;} td #err{ color:#FF0000; font-weight:bold;} </style> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" > <h3><font face="Georgia" color="#000066" size="+2">Registeration</font></h3> <?php if (count($errors) > 0): echo "<p style='color:#ff0000'>*The following errors ocurred:</p>"; endif; ?> <table width="" border="1"> <tr> <th scope="row">Firstname:</th> <td><input name="fname" type="text" id="fname" size="28" value="<?php echo htmlentities($input['fname'])?>" /></td> <td id="err"><?php echo $errors['fname'] ?></td> </tr> <tr> <th scope="row">Lastname:</th> <td><input name="lname" type="text" id="lname" size="28" value="<?php echo htmlentities($input['lname'])?>" /></td> <td><?php echo $errors['lname'] ?></td> </tr> <tr> <th scope="row">Date of Birth:</th> <td> <select name="days" size="1" id ="days" > <option value='-------'>--Day--</option> <?php /* day starts here*/ (array)$num_days; foreach ($num_days as $day): printf("<option value=\"%s\" %s>%s</option>",$day,($days==$day ? "selected='selected'" : ""), $day); endforeach; /* day ends and months start here*/ ?> </select> <select name="" size="1" id =""> <?php /* month ends and starts here*/ ?> </select><select name="" size="1" id =""> <?php ?> </select> <br /><small style="text-align:center; color:#006600;">dd-mm-yyy</small> </td> <td><?php echo $errors['date'] ?></td> </tr> <tr> <th scope="row">Sex:</th> <td> <select name="" size="1" id =""> <?php /* Sex selection starts here;*/ /* Sex selection starts here; */ ?> </select></td> <td><?php echo $errors['sex'] ?></td> </tr> <tr> <th scope="row">Email:</th> <td><input name="email" type="text" id="email" size="28" value="<?php echo htmlentities($input['email']) ?>"/></td> <td><?php echo $errors['email'] ?></td> </tr> <tr> <th scope="row">Password:</th> <td><input name="password" type="password" id="password" size="28" value="<?php echo htmlentities($input['password']) ?>"/></td> <td><?php echo $errors['password'] ?></td> </tr> <tr> <th scope="row">Comfirm Password:</th> <td><input name="password2" type="password" id="password2" size="28" value="<?php echo htmlentities($input['password2']) ?>"/></td> <td> </td> </tr> <tr> <th scope="row"> </th> <td> </td> <td> </td> </tr> <tr> <th scope="row">I agree:</th> <td><input name="agree" type="checkbox" id="agree" value="<?php echo $input['agree']='agree'?>" /></td> <td><?php echo $errors['agree'] ?></td> </tr> <tr> <th scope="row"><input name="action" type="hidden" id="submitted" value="TRUE" /></th> <td><input name="add_newuser" type="submit" id="submit" value="I accept, Register me" /></td> <td> </td> </tr> </table> </form> </body> </html> <?php } function register_user($input){ include "../c-library/database.inc.php"; // $input = $_REQUEST; $input['fname'] = mysql_escape_string(stripslashes($input['fname'])); $input['lname'] = mysql_real_escape_string(stripslashes($input['lname'])); //$input['day'] $input['date'] = $input['year'].''.$input['month'].''.$input['day']; $input['sex'] = $input['sex']; $input['email'] = mysql_real_escape_string($input['email']); $input['password'] = mysql_real_escape_string(md5($input['password'])); $input['uid'] = uniqid(rand(16,32),true); $qr ="insert into users(id,Firstname,Lastname,Date_of_Birth,Sex,Email,Password,Userid) values('null','$input[fname]','$input[lname]','$input[date]','$input[sex]','$input[email]','$input[password]','$input[uid]')"; $results = mysql_query($qr,$sdayb); return $results; mysql_close($sdayb); echo "thanks";//header("Location: thankyou.html"); } /*ex. user enters - 19/11/1980 $var = explode('/', '19/11/1980'); $sdayd = $var[0]; $mm = $var[1]; $yyyy = $var[2]; */ if(isset($_POST['add_newuser'])): $inputs = $_POST; $setErrors = array(); if(!check_formerr($inputs, $setErrors)): viewForm($inputs, $setErrors); else: register_user($inputs); endif; else: viewForm(null, null); endif; ?> use in form fields - onBlur="chkalpha(this)" function chknum(field) { var valid = "0123456789"; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only numeric data is accepted!"); field.value=""; field.focus(); field.select(); } } function chkalpha(field) { var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only alphabetic data is accepted!"); field.value=""; field.focus(); field.select(); } } function chkalphanum(field) { var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_-. "; var ok = "yes"; var temp; for (var i=0; i<field.value.length && ok == "yes"; i++) { temp = "" + field.value.substring(i, i+1); if (valid.indexOf(temp) == "-1") { var ok = "no"; } } if (ok == "no") { alert("Invalid entry! Only alphanumeric data is accepted!"); field.value=""; field.focus(); field.select(); } } 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 Ill tell you the story and then simplify it ok i have a computer site that you can build your own computer and whatnot but i just recently thought about how not everyone knows which parts are needed in a computer... my first design of the site had the name of the part in the select box as default but now i removed the name of each part outside of the select boxes but the problem now is i need some type of onLoad event to happen when the page loads to call out the functions that are associated with the selected boxes...... i have 2 fuctions in an external js file Code: function swapImage(sel,id){ document.getElementById(id).src = sel.value.split('#')[1]; } and Code: function Calculate(){ var a = parseFloat(document.comp.caseselect.value.split('#')[0]); var b = parseFloat(document.comp.powersupply.value.split('#')[0]); var sum = a+b; document.getElementById("total").innerHTML = '$'+sum; } when someone selects an item it adds the price to the price of other selected items and shows the total price elsewhere on the page... also shows a picture of the selected item on the page.. im just going to show the first select box to show you how all my select boxes are written Code: <p align="left">CASE</p> <center> <select name="caseselect" style="width:625px" onchange="Calculate(); swapImage(this,'caseimg');"> <option value="50#COOLER MASTER Elite 310red.jpg" selected="1">COOLER MASTER Elite 310 Red ($50.00)</option> <option value="50#COOLER MASTER Elite 310blue.jpg">COOLER MASTER Elite 310 Blue ($50.00)</option> <option value="50#COOLER MASTER Elite 310orange.jpg">COOLER MASTER Elite 310 Orange ($50.00)</option> <option value="50#COOLER MASTER Elite 310silver.jpg">COOLER MASTER Elite 310 Silver ($50.00)</option> </select> *not that it matters but yes there is an ending center in my html but its at the end of the group the image is sent here Code: <img src="start.jpg" id="caseimg" /> and the price is sent here Code: <span style="color:black; font-size:20pt">YOUR PRICE UPDATE</span><br /> <span id="total" style="color:white; font-size:32pt">$0 Nothing Selected</span> code works perfectly fine ONCE YOU SELECT SOMETHING ELSE but i need it to work when the page loads I am trying to do a custom add to cart to use with paypal and need to utilize javascript to achieve inserting some code or a weight value per the paypal forms' options choice. Here is my dilemma, All of my items have multiple weights, for instance the below example called Aqua Max 100 comes in .5lbs, 1.5lbs., 10lbs., 20lbs., and 50lbs. Paypal allows you to enter weight but it's one weight per item and I would have to create 5 Paypal buttons just for this one item to calculate the different weights per zip code. I need help making javascript insert the following code within the paypal forms' code upon option select before clicking submit? <input type="hidden" name="weight" value=".5"> <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="1.5"> <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="10 <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="20 <input type="hidden" name="weight_unit" value="lbs"> <input type="hidden" name="weight" value="50 <input type="hidden" name="weight_unit" value="lbs"> The code I came up with is wrong as I'm getting an error but I was originally trying to make it enter a weight using a hidden fillable number and without any real javascript training, just alot of googling but I think I'm pretty close. Please take a look at the code I've came up with so far and maybe point me in the correct direction: <html> <body> <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="business" value="test@test.com"> <input type="hidden" name="currency_code" value="USD"> <input type='hidden'text' name='amt' id='amt' value="0.00"/> <table> <tr> <td> <input type="text" name="on0" value="Aqua Max 100">Aqua Max 100</td></tr> <tr><td> <select name="os0" onChange="getamt()"> <option value="select">Please Select</option> <option value="1/2 lb.">1/2 lb. $3.99 USD</option> <option value="1 - 1/2 lbs">1 - 1/2 lbs $7.59 USD</option> <option value="10 lbs.">10 lbs. $25.80 USD</option> <option value="20 lbs.">20 lbs. $42.75 USD</option> <option value="50 lbs.">50 lbs. $86.20 USD</option> </select></td></tr> </table> <script type="text/javascript"> function getamt() { var sh=0; var choice = document.getElementById("os0").selectedIndex; if (choice == 0) { sh=0; } if (choice == 1) { sh=.5; } if (choice == 2) { sh=1.5; } if (choice == 3) { sh=10; } if (choice == 4) { sh=20 } if (choice == 5) { sh=50.00; } document.getElementById("on0").value=sh; } </script> <input type="image" src="https://images.paypal.com/images/sc-but-03.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> </body> </html> 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> I've been using a script for verifying forms across several pages, and I've run into a page where it won't work the way it is. It's a form that loops through and creates a set of fields over and over, depending on the number of attendees. I'm assuming this disrupts the form verification because the fields get generated with the same id. I think I need to find another way to make sure the user enters valid and complete information. Here's what I've been using: Code: function myForm(){ // Make quick references to our fields var fname = document.getElementById('fname'); var lname = document.getElementById('lname'); var birth_month = document.getElementById('birth_month'); var birthday = document.getElementById('birthday'); var birthyear = document.getElementById('birthyear'); // Check each input in the order that it appears in the form! if(isAlphabet(fname, "Please enter only letters for your first name")){ if(isAlphabet(lname, "Please enter only letters for your last name")){ if(madeSelection(birth_month, "Pleace choose a birth month")){ if(madeSelection(birthday, "Please choose a birth day")){ if(madeSelection(birthyear, "Please choose a birth year")){ return true; } } } } } 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 madeSelection(elem, helperMsg){ if(elem.value == ''){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } </script> <!-- the snippet that creates the form fields is he --> $count = $line; $i = 1; while ($i <= $count) { $i++; /* the printed value would be $i before the increment (post-increment) */ $x = $i-1; ?> <form name="register1" class="registration_form" method="post" action="register2.php" target="_self" onsubmit="return myForm()"> First Name<br><input type="text" name="kfname[]" id="fname" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" /><br> Kid's Last Name<br><input type="text" name="klname[]" id="lname" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" /><br> Birthdate<br> <select style="width:75px;" id="birth_month" name="bdate2[]" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" > <option value="">month</option> <option value="01">Jan</option> <option value="02">Feb</option> <!-- etcetera --> </select> <select style="width:57px;" id="birthday" name="bdate[]" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" > <option value="">day</option> <option value="01">01</option> <option value="02">02</option> <!-- etcetera --> </select> <select style="width:60px;" id="birthyear" name="bdate3[]" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" > <option value="">year</option> <option value="1993">1993</option> <option value="1994">1994</option> <!-- etcetera --> </select> </form> Good Day, I am new to this forum so i hope i am posting in the correct place. I have been working on a form validation in javascript where the error messages should be displayed beside the form field (no alerts!). The error message is displayed when i iuse alerts but not otherwise. I have included a code snippet below. Any help will be greatly appreciated. Thanks in advance. function validation() { //alert('made it here'); var fName = document.getElementById('txtFname').value; var fNameId = document.getElementById('txtFname'); if(validateName(fName,fNameId)){ return true; } return false; } function validateName(name,id){ var ck_name = /^[A-Za-z0-9 ]{6,20}$/; //alert('made it it here'); if(!ck_name.test(name)) { //alert("Invalid"); var message = "Should be between 3 and 20 characters and made up of etters, numbers or - symbol"; //create a new span element var sp = document.createElement('span'); //assign the new span element a class sp.className = 'error'; //assign span some content sp.appendChild(document.createTextNode(message)); //place the message after the form field document.body.insertBefore(sp, id); name.value=""; name.focus(); return false; } return true; } I'm having trouble changing the font color of my labels ONLY when I stop the form from submitting due to blank fields. I'm not sure whether if just changing my CSS will achieve what I want, or am I going to have to add something to my if else statement, or both? I would think I would need to change CSS to : label.onfocus { color:red; } but a little confused on what else. Any help would be appreciated! Code: <?xml version="1.0" encoding="UTF-8"?> <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Adam's Form Validation</title> <script type="text/javascript"> //<![CDATA[ function validate() { var errors = new Array( ); for( var x = 0 ; x < document.forms[ 0 ].elements.length ; x++ ) { if( document.forms[ 0 ].elements[ x ].type == "text" ) { if (document.forms[ 0 ].elements[ x ].value == "") { errors.push("*"+"The " + document.forms[ 0 ].elements[ x ].name + "field cannot be blank\n"); document.forms[ 0 ].elements[ x ].className = "in_error"; } } if( document.forms[ 0 ].elements[ x ].type == "select-one" ) { if(document.forms[ 0 ].elements[ x ].selectedIndex !== 2) { errors.push("*"+"The " + document.forms[ 0 ].elements[ x ].name + " field cannot be blank\n"); document.forms[ 0 ].elements[ x ].className = "in_error"; } } } if( errors.length == 0 ) { return true; } else { clear_errors( ); show_errors( errors ); return false; } } function clear_errors( ) { var div = document.getElementById( "errors" ); while (div.hasChildNodes( ) ) { div.removeChild(div.firstChild); } } function show_errors( errors ) { var div= document.getElementById( "errors" ); for( var x = 0 ; x < errors.length ; x++) { var error = document.createTextNode( errors[ x ] ); var p = document.createElement( "p" ); p.appendChild( error); div.appendChild( p ); } } window.onload = function () { document.forms[ 0 ].onsubmit = validate; } //]]> </script> <style type="text/css" media="screen"> #errors { color: #F00; } .in_error { border: 2px outset #f00; } </style> </head> <body> <h1>Adam's Form Validation</h1> <div id="errors"></div> <form action="http://ingenio.us.com/examples/echo" method="post"> <p> <label for="firstname">First Name: </label> <input type="text" name="firstname" value="" id="firstname"/> </p> <p> <label for="lastname">Last Name: </label> <input type="text" name="lastname" value="" id="lastname"/> </p> <p> <label for="middle">Middle Inital: </label> <input type="text" name="middle" value="" id="middle" maxlength="1" size="4"/> </p> <p> <label for="address">Street Address: </label> <input type="text" name="address" value="" id="address"/> </p> <p> <label for="city">City: </label> <input type="text" name="city" value="" id="city"/> </p> <p> <label for="state">State: </label> <input type="text" name="state" value="" id="state" maxlength="2" size="4"/> </p> <p> <label for="zip">Zip Code: </label> <input type="text" name="zip" value="" id="zip" maxlength="5" size="7"/> </p> <p> <label for="username">User Name: </label> <input type="text" name="username" value="" id="username"/> </p> <p> <label for="password">Password: </label> <input type="text" name="password" value="" id="password"/> </p> <p> <label for="password2">Confirm Password: </label> <input type="text" name="password2" value="" id="password2"/> </p> <p> <label for="agreement">Terms and Conditions:</label> <select name="agreement" id="agreement"> <option></option> <option>No, I have not read the user agreement</option> <option>Yes, I have read and understand the user agreement</option> </select> </p> <p> <input type="submit" value="Register"/></p> </form> </body> </html> Hi, I have a form where I want to check that at least one email address has been entered on one line. The html form is below and users are given the option to add additional lines to the form using the addRowToTable function also below. How do I do this? I've tried several ways but because lines are added to the form, it doesn't work if you check over all 10 lines, when you're only showing 5. Form: <form action="<?=$_SERVER['PHP_SELF']?>" method="post" onsubmit="check_form();"name="form"> <input type="hidden" name="migrate" value="1" /> <table id="migration_emails" > <tr><td><input type="text" name="email_account_1" id="email_account_1" size="40"><input type="button" onclick="addRowToTable();" name="add" value="Add text box" /></td></tr> <tr><td><input type="text" name="email_account_2" id="email_account_2" size="40"></td></tr> <tr><td><input type="text" name="email_account_3" id="email_account_3" size="40"></td></tr> <tr><td><input type="text" name="email_account_4" id="email_account_4" size="40"></td></tr> <tr><td><input type="text" name="email_account_5" id="email_account_5" size="40"></td></tr> </table> <p><input type="submit" value="Migrate" /></p> </form> Add row to table function: function addRowToTable() { var tbl = document.getElementById('migration_emails'); var lastRow = tbl.rows.length; var iteration = lastRow + 1; if(iteration <= 10) { var row = tbl.insertRow(lastRow); var cellLeft = row.insertCell(0); var el = document.createElement('input'); el.type = 'text'; el.name = 'email_account_' + iteration; el.id = 'email_account_' + iteration; el.size = 40; cellLeft.appendChild(el); } else { document.form.add.disabled=true; alert('Sorry, a maximum of 10 accounts can be added at one time.'); } } Hi everyone, this is my first thread on the forum. . I am having issues with a form I am trying to validate. It validates on a remote server (WAMP) I have set up on my laptop but when I attempt it on another server it will not work. The code is as follows: <script type="text/javascript"> function validateForm() { var x=document.forms["pass"]["npass"].value var y=document.forms["pass"]["password"].value if (x==null || x=="") { alert("Please enter your new password"); return false; } if (y==null || y=="") { alert ("Please confirm your new password"); return false; } else alert("Some message"); } </script> <form name="pass" action="#" method="post" onsubmit="validateForm()"> <input name="npass" type="password"> <input name="password" type="password"> <input type="submit" value="Submit"> My browser is also configured to accept javascript. Any help would be very much appreciated. Thanks in advance, tdsrogers |