JavaScript - Form No Longer Submits After Adding A Second Form
Hello,
I am using a simple form to submit values to another website. This has been working without any problems. I now have added a second form to the page. I have separated the text boxes and duplicated the information from one form to another. The problem is, when I click on the link that use to submit the information, nothing happens. Before the addition of the new form a new window would open with the search that I had submitted. Am I missing something to point to one form or the other? The following is the code that i am using in the form that no longer submits. Thanks in advance for any help. Code: <script language="javascript"> function submitPostLink() { document.postlink.submit(); } </script> <form action="http://wcca.wicourts.gov/simpleCaseSearch.do;jsessionid=61EFDA464D938EB53461CABB6EFC7D3B.renderHTTP/1.1" name="postlink" method="post" target="_blank"> <input type="hidden" name="partyName.lastName" id="ccapLAST"> <input type="hidden" name="partyName.firstName" id="ccapFIRST"> <input type="hidden" name="partyName.middleName" id="ccapMIDDLE"> <input type="hidden" name="partyName.showMissingMiddleNames" value="true"> <input type="hidden" name="recordsPerPage" value="25"><br> <a onclick="submitPostLink()" href="#" a>SEARCH</a> </form> Similar TutorialsHello 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 } }); }); I have a form, on which I have multiple checkboxes and text fields. Now I want that the form can't submit untill at least 1 checkbox is selected or a text field is filled. But even with the javascript validation I already have the form still submits. Any help on this one? Here is the whole page on which the checkboxes, text fields and javascript validation a PHP Code: <script type="text/javascript" language="javascript"> function checkCheckBoxes() { if (document.form2.nbs_vmb[].checked == false) { alert ('Select at least checkbox to make a selection!'); return false; } else { return true; } </script> <div id="left2"> <div id="left_02"> <div id="toppage"> <h3><?php echo $tcm_label[59]; ?></h3> </div> <div style="margin:0px 1px 0px 1px"> <form id="form_ins_contact" onsubmit="return checkCheckBoxes();" name="form2" action="test.php" method="POST" > <table width="680" height="350" border="0" align="center" cellpadding="0" cellspacing="2"> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[36]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_lid_vmb" /></td> <td class="td_no_border2"></td> <td class="td_no_border2"></td> </tr> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[37]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_selfburns" /></td> <td align="right"><strong><?php echo $tcm_label[29]; ?></strong></td> <td class="td_no_border"><input name="nbs_zip" type="text" id="nbs_zip" maxlength="6" size="6" /></td> </tr> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[40]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_profrelatie" /></td> <td align="right"><strong><?php echo $tcm_label[60]; ?></strong></td> <td class="td_no_border"><input name="nbs_contact_year" type="text" id="nbs_contact_year" maxlength="4" size="4" /></td> </tr> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[42]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_revalinet" /></td> <td align="right"><strong><?php echo $tcm_label[38]; ?></strong></td> <td class="td_no_border" width="194"><input name="nbs_year" type="text" id="nbs_year" maxlength="4" size="4" /></td> </tr> <tr> <td align="right"><strong><?php echo $tcm_label[44]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_juridischehulp" /></td> <td align="right"><strong><?php echo $tcm_label[41]; ?></strong></td> <td class="td_no_border" width="194"><input name="nbs_vmb[]" type="checkbox" value="nbs_psychonet" /></td> </tr> <tr> <td align="right"><strong><?php echo $tcm_label[45]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_nomail" /></td> <td align="right"><strong><?php echo $tcm_label[43]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_reintegranet" /></td> </tr> <tr> <td align="right" class="td_no_border2"> </td> <td class="td_no_border2"> </td> <td></td> <td class="td_no_border2"><img src="../images/intra icon.png" width="96" height="96" /></td> </tr> </table> <table width="281" border="0" align="center" cellpadding="0" cellspacing="2"> <tr> <td align="center" class="td_no_border2" nowrap="nowrap"> <input type="submit" name="submit" class="buttons" value="Export Selecties" /> </td> </tr> </table> </form> </div> </div> </div> Thanks in advanced. Hi all, Maybe I'm missing something simple here, but for some reason this form validates in both IE and Firefox, but it doesn't submit in IE. Little yellow exclamation icon appears on the status bar on form submit. Any help would be great. Thanks! Code: /* Creation Date: Dec 8, 2009 Description: */ function validate_school_form() { var valid = false; var error = ""; if (element("fname").value.length < 1 ){ error += "Please enter your first name.<br/>"; element("fname").style.border = "1px solid red"; } else { element("fname").style.border = ""; } if ( element("lname").value.length < 1 ){ error += "Please enter your last name.<br/>"; element("lname").style.border = "1px solid red"; } else { element("lname").style.border = ""; } if ( !validate_email_address(element("email").value) ){ error += "Please enter a valid email address.<br/>"; element("email").style.border = "1px solid red"; } else { element("email").style.border = ""; } if ( element("addr").value.length < 1 ){ error += "Please enter your street address.<br/>"; element("addr").style.border = "1px solid red"; } else { element("addr").style.border = ""; } if ( element("zip").value.length != 5 || isNaN(element("zip").value) ){ error += "A zip code must be 5 digits.<br/>"; element("zip").style.border = "1px solid red"; } else { element("zip").style.border = ""; } if ( element("city").value.length < 1 ){ error += "Please enter your city.<br/>"; element("city").style.border = "1px solid red"; } else { element("city").style.border = ""; } if ( element("state").value.length < 1 ){ error += "Please enter your state.<br/>"; element("state").style.border = "1px solid red"; } else { element("state").style.border = ""; } if (( element("phone1").value.length != 3 ) || ( element("phone2").value.length != 3 ) || ( element("phone3").value.length < 4 ) ){ error += "Please enter a valid phone number.<br/>"; element("phone1").style.border = "1px solid red"; element("phone2").style.border = "1px solid red"; element("phone3").style.border = "1px solid red"; } else { element("phone1").style.border = ""; element("phone2").style.border = ""; element("phone3").style.border = ""; } if ( element("gender").selectedIndex == 0 ){ error += "Please enter your gender.<br/>"; element("gender").style.border = "1px solid red"; } else { element("gender").style.border = ""; } if ( element("birth_day").selectedIndex == 0 ){ error += "Please enter a valid day of birth.<br/>"; element("birth_day").style.border = "1px solid red"; } else { element("birth_day").style.border = ""; } if ( element("birth_month").selectedIndex == 0 ){ error += "Please enter a valid month of birth.<br/>"; element("birth_month").style.border = "1px solid red"; } else { element("birth_month").style.border = ""; } if ( element("birth_year").selectedIndex == 0 ){ error += "Please enter a valid year of birth.<br/>"; element("birth_year").style.border = "1px solid red"; } else { element("birth_year").style.border = ""; } if ( element("program_type").selectedIndex == 0 ){ error += "Please enter your program of interest.<br/>"; element("program_type").style.border = "1px solid red"; } else { element("program_type").style.border = ""; } if ( element("level_of_education").selectedIndex == 0 ){ error += "Please enter your level of education.<br/>"; element("level_of_education").style.border = "1px solid red"; } else { element("level_of_education").style.border = ""; } if ( error != "" ){ alert('Error! Please fix the marked fields for missing or wrong information.'); return false; } else { var d = new Date(); var o = element("birth_year"); var birth_year = o.options[o.selectedIndex].value; if (birth_year <= (d.getFullYear()-22)) { submit_school_form(); } else { goToStep3(); } } } function submit_school_form() { var o = ""; var text = "http://xxxxxx.com/engine/directpost?"; //var text = "../response2.php?"; text += "CID=" + encodeURIComponent(element("CID")); text += "first=" + encodeURIComponent(element("fname").value); text += "&last=" + encodeURIComponent(element("lname").value); text += "&mail_addr_1=" + encodeURIComponent(element("addr").value); text += "&mail_city=" + encodeURIComponent(element("city").value); text += "&mail_stateprov=" + encodeURIComponent(element("state").value); text += "&mail_postalcode=" + encodeURIComponent(element("zip").value); text += "&email=" + encodeURIComponent(element("email").value); var phone = element("phone1").value + element("phone2").value + element("phone3").value text += "&home_phone=" + encodeURIComponent(phone); o = element("birth_day"); var birth_day = o.options[o.selectedIndex].value; text += "&bdate_day=" + encodeURIComponent(birth_day); o = element("birth_month"); var birth_month = o.options[o.selectedIndex].value; text += "&bdate_month=" + encodeURIComponent(birth_month); o = element("birth_year"); var birth_year = o.options[o.selectedIndex].value; text += "&bdate_year=" + encodeURIComponent(birth_year); o = element("gender"); var gender = o.options[o.selectedIndex].value text += "&gender=" + encodeURIComponent(gender); o = element("program_type"); var program_type = o.options[o.selectedIndex].value text += "&program_type=" + encodeURIComponent(program_type); o = element("level_of_education"); var level_of_education = o.options[o.selectedIndex].value text += "&level_of_education=" + encodeURIComponent(level_of_education); text += "&user_ip=" + encodeURIComponent(element("user_ip").value); text += "×tamp=" + encodeURIComponent(element("timestamp").value); text += "&domain=" + encodeURIComponent(element("domain").value); var complete = sendData(text); // if (complete) { goToStep3(); // } } function goToStep3(){ window.location = "redirect3.php"; } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your webbrowser does not support AJAX"); return false; } } } return xmlHttp; } function sendData(text) { xmlHttp=GetXmlHttpObject(); var url = 'http://xxxxxx.com/engine/directpost?'+text; xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { return true; } else { return false; } } } xmlHttp.open('GET', url, true); xmlHttp.send(null); } THanks! hi dears, I'm trying to do simple form validation. But the form submits right after validated! at FireFox only. as i tried it at IE it works fine. condition: if return false the event must be stop, killed submitting the form value's. my form is: Code: <form action="index.php" id="cat_form" method="post" name="cat_form" onsubmit="return cats();"> my js is: Code: function cats() { if (document.cat_form.txttitle.value=="") { alert ("Sorry, Don't keep it blank!!") cat_form.txttitle.focus(); return false; } else if (document.farticle.txtperpg.value==0) { alert("Sorry, Value must be grater than Zero"); cat_form.txtperpg.focus(); return false; } else { return true; } } Any Idea ? 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> Hi, I have a JS function which calculates "Amount" (Thanks to abduraooft and Philip M) frm.Amount.value=order_total*100; Then I have a (hidden) form input which "displays" the "Amount" <INPUT TYPE=HIDDEN NAME="Amount"> Now I would need a URL which includes the same value that is displayed in the input field (="Amount"). In practice the URL looks like this: https://www.XXX.com/payment?Amount=[this is where I would need the "Amount" to be displayed] How can I archive this? As you might have guessed I'm no pro in these matters when 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? I am trying to develop a function that creates a certain number of form elements based on a certain number that a user inputs. It does not do what I want it to do (obviously). The problem lies within the TextBoxAppear() function. The function worked when I tested it by adding just text (document.getElementByID('leftcolumn').innerHTML = "<p>test function</p>" so I know for a fact whatever I added to the function is the problem. What has been added to the function and needs fixing is in BOLD Code: <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Exercise 4</title> <style type = "text/css"> #leftcolumn { width: 300px; border: 1px solid red; float: left} #rightcolumn { width: 300px; border: 1px solid red; float: left} </style> <script> function start() { var button = document.getElementById( "submitButton" ); button.addEventListener( "click", TextBoxAppear, false ); } function TextBoxAppear() { var numberOfValuesInput = document.getElementByID( 'NumberOfValuesField' ); var numberOfValues = parseFloat( numberOfValuesInput.value ); var textBoxCreation = "<form action ="http://www.deitel.com"><p>"; for ( var i = 1; i < numberOfValues; ++i ) { textBoxCreation += "<label>Value" + i + ":<input id = 'Value" + i + "' type = 'text'></label>"; } textBoxCreation += "<input id = "calculateButton" type = "button" value = "Calculate"></p></form> document.getElementById('leftcolumnn').innerHTML = textBoxCreation; } window.addEventListener( "load", start, false ); </script> </head> <body> <form action ="http://www.deitel.com"> <p><label>Number of values to be calculated: <input id = "numberOfValuesField" type = "text"></label> <input id = "submitButton" type = "button" value = "Submit"></p> </form> <div id ="leftcolumn"><p>test left column</p></div> <div id ="rightcolumn"><p>test right column</p></div> </body> </html> I have the following code that I wrote myself (except for the function isNumberKey). However, I don't know how to actually add the numbers together. My plan is to store the value entered in the forms as a variable, then manipulate the variables to get my final number. The final number would be stored in variable named Total and would be displayed after Total: at the bottom of my page. Could anyone help me? I can provide additional information if you need it. Code: <HTML> <TITLE>Magazine Prices </TITLE> <BODY> <SCRIPT language=Javascript> <!-- Price = oForm.elements["price"].value; Quantity = oForm.elements["quantity"].value; Subtotal = oForm.elements["subtotal"].value; Shipping = oForm.elements["shipping"].value; function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } //--> </SCRIPT> <!-- Price * Quantity = Subtotal. Subtotal value should fill in automatically in the Subtotal input field. Subtotal * Shipping = Total. //--> <TABLE> <TR><TD>Price: </TD><TD><INPUT id="Price" name="Price" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> </TD></TR> <TR><TD>Quantity:</TD> <TD><INPUT id="Quantity" name="Quantity" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> </TD></TR> <TR><TD>Subtotal:</TD> <TD><INPUT id="Subtotal" name="Subtotal" onkeypress="return isNumberKey(event)" type="text" readonly="readonly" name="txtChar"> </TD></TR> <TR><TD>Shipping:</TD> <TD><INPUT id="Shipping" name="Shipping" onkeypress="return isNumberKey(event)" type="text" value="10%" readonly="readonly" name="txtChar"> </TD></TR> </TABLE> <b>Total: </b> </BODY> </HTML> Good morning! Hopefully somebody can help me with this javascript question. (No knowledge of Google Anayltics needed for this.) I'm adding Google Analytics 'Event Tracking' javascript to a typical 'Add to Cart' button. The customer enters desired quantity in the text box and clicks the 'Add to Cart' button to order. I would like to use the Event Tracking javascript to record the button click - plus the Value entered in the text box - as one event. Here's the code for the form (the text box and 'Add to Cart' button code lines are bold): Code: <form method="post" action="http://www.yoursite.com/mm5/merchant.mvc?"> <input type="hidden" name="Screen" value="BASK" /> <input type="hidden" name="Product_Code" value="yourproductcode" /> <input type="hidden" name="Action" value="ADPR" /> <label for="quantity">Quantity:</label> <input type="text" name="quantity" value="0" /> <input type="submit" value="Add To Cart" /> </form> I came up with this javascript for the Event Tracking (to be inserted somewhere above): Code: onClick="_gaq.push(['_trackEvent', 'OrderForms', 'AddToCart', 'yourproductcode', document.getElementByName('quantity').value]);" I'm wondering where I would enter this javacript code inside the form code to pick up both the button click - plus the quantity? You'll notice that I'm using 'getElementByName' to extract 'quantity' from the text box and record its 'value'. If I enter this javascript on the 'Add to Cart' line - right after "Add to Cart", would 'quantity' still get picked up upon button-click - since it's all on the same form? Or would it be a problem because 'quantity' is contained in a different <input> container? Thanks! Any help is greatly appreciated. IB Hello guys (and girls) I am messing with this whole day, 'cos I wanted to try and figure this out by myself instead of going on forums. I failed, as you may see. So, to cut it short: I needed to calculate my prices on-the-fly and display it in textbox with javascript. Well I did succeed with values of radio button an checbox, but as i know very little javascript, I don't know how to expand the code i got from he http://javascript.internet.com/forms...e-refresh.html So what I would LOVE to know, is how can I make this happen: I have a textbox: Code: <input type="text" name="podstranice" size="19" class="podstr" onkeyup="this.form.total.value=calculateTotal(this);"> and when a user inputs a number in it, javascript multiplies it with some other number, say 10 (its a price*quantity thing) and adds it to the total price along with data from checkboxes and radio buttons. And so, this is my javascript. It is basically identical to one on the link, but you can view it better this way I think. Code: // Calculate the total for items in the form which are selected. function calculateTotal(inputItem) { with (inputItem.form) { // Process each of the different input types in the form. if (inputItem.type == "radio") { // Process radio buttons. // Subtract the previously selected radio button value from the total. calculatedTotal.value = eval(calculatedTotal.value) - eval(previouslySelectedRadioButton.value); // Save the current radio selection value. previouslySelectedRadioButton.value = eval(inputItem.value); // Add the current radio button selection value to the total. calculatedTotal.value = eval(calculatedTotal.value) + eval(inputItem.value); } else { // Process check boxes. if (inputItem.checked == false) { // Item was uncheck. Subtract item value from total. calculatedTotal.value = eval(calculatedTotal.value) - eval(inputItem.value); } else { // Item was checked. Add the item value to the total. calculatedTotal.value = eval(calculatedTotal.value) + eval(inputItem.value); } } elseif // Total value should never be less than 0. if (calculatedTotal.value < 0) { InitForm(); } // Return total value. return(formatCurrency(calculatedTotal.value)); } } // Format a value as currency. function formatCurrency(num) { num = num.toString().replace(/\$|\,/g,''); if(isNaN(num)) num = "0"; sign = (num == (num = Math.abs(num))); num = Math.floor(num*100+0.50000000001); cents = num%100; num = Math.floor(num/100).toString(); if(cents<10) cents = "0" + cents; for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3)); return (((sign)?'':'-') + num + '.' + cents + ' kn'); } // This function initialzes all the form elements to default values. function InitForm() { // Reset values on form. document.selectionForm.total.value='$0'; document.selectionForm.calculatedTotal.value=0; document.selectionForm.previouslySelectedRadioButton.value=0; // Set all checkboxes and radio buttons on form to unchecked. for (i=0; i < document.selectionForm.elements.length; i++) { if (document.selectionForm.elements[i].type == 'checkbox' | document.selectionForm.elements[i].type == 'radio') { document.selectionForm.elements[i].checked = false; } } } I don't want to overspam my post with more code, so I hope this is all you need, at least for now. THANK YOU very much in advance. Hi, firstly I apologise if the title of this thread isn't quite accurate. I'm sure you've all heard it before but I am a complete newbie to Javascript so again: apologies if this is boring and tiresome to even read, let alone help with! I have been asked to make some changes to a form that uses Javascript for the form validation. There is a 'function' that contains the variables of the various form fields and then further code to raise 'alerts' if one of the fields on the form hasn't been filled in. My problem is that for some reason I am unable to add an extra variable to this code after the field of 'County' (this will hopefully make sense when you see the code / link...) and I am stumped as to why. I am able to add variables for all of the other required fields except for 'Postcode' after 'County'. This is the case for both forms. The link is he http://samdelara.co.uk/previews/banq...ation-form.htm and the code I am trying edit is below: function checkAvailibility() { // re-calculate... calculate (); if ( isName() && isAddress1() && isTown() && isCounty() && isPostcode() && isYourEmail() && isFuncDate() && somethingToQuoteFor() && isYourEmailValid() ) { document.ordersummary.emailQuote.value = "No"; setValue(); return true; } else { return false; } } function isName() { if (document.ordersummary.Name.value=="") { alert ("\n Please Enter Your Name") document.ordersummary.Name.focus(); return false; } return true; } function isAddress1() { if (document.ordersummary.Address1.value=="") { alert ("\n Please Enter Your Address") document.ordersummary.Address1.focus(); return false; } return true; } function isTown() { if (document.ordersummary.Town.value=="") { alert ("\n Please Enter Your Town") document.ordersummary.Town.focus(); return false; } return true; } function isCounty() { if (document.ordersummary.County.value=="") { alert ("\n Please Enter Your County") document.ordersummary.County.focus(); return false; } return true; } function isPostcode() { if (document.ordersummary.Postcode.value=="") { alert ("\n Please Enter Your Postcode") document.ordersummary.Postcode.focus(); return false; } return true; } function isYourEmail() { if (document.ordersummary.YourEmail.value=="") { alert ("\n Please Enter Your Email") document.ordersummary.YourEmail.focus(); return false; } return true; } function isFuncDate() { if (document.ordersummary.FuncDate.value=="") { alert ("\n Please Enter Your Function Date") document.ordersummary.FuncDate.focus(); return false; } return true; } function isemailonly() { if (document.ordersummary.emailonly.value=="") { alert ("\n Please Enter Your Email Address") document.ordersummary.emailonly.focus(); return false; } return true; } Any help with this would be very much appreciated and once again, I apologise for my distinct lack of knowledge in this area! Sam Hey CF, I'm currently working on a website called 'eXtreme Gaming' I've almost completed it, apart from two things. - Adding two values on my checkout page for the Grandtotal (I've tried everything, but I'm too much of a noob and have probably missed something small). - Validation of forms (I don't know where to start here, I've looked on w3schools for tuts etc but I'm having difficulty incorporating it on my site) I'm going to put the code for my checkOut page only, if you are able to help me many thanks in advance. [quote] Code: <HTML> <HEAD> <script language="JavaScript" src="laptopsCookie.js"> </script> <script language="JavaScript" src="desktopsCookie.js"> </script> <script language="JavaScript"><!-- function calculateTotalPurchaseLaptop(formRef) { var laptopTotal=0; for (var i=0; i<LaptopListPurchase.length/2;i++) { var subTotal = formRef.elements['quantity'+i].value * formRef.elements['price'+i].value; formRef.elements['subTotal'+i].value = subTotal.toFixed(2); // document.orderForm2.grandTotal.value = document.orderForm.laptopTotal.value + document.orderForm2.desktopTotal.value laptopTotal += subTotal; } formRef.laptopTotal.value = laptopTotal.toFixed(2); } //--></script> <script language="JavaScript"><!-- function calculateTotalPurchaseDesktop(formRef) { var desktopTotal=0; for (var i=0; i<DesktopListPurchase.length/2;i++) { var subTotal = formRef.elements['quantity'+i].value * formRef.elements['price'+i].value; formRef.elements['subTotal'+i].value = subTotal.toFixed(2); desktopTotal += subTotal; } formRef.desktopTotal.value = desktopTotal.toFixed(2); } //--></script> <script language="Javascript"><!-- function checkform() { if (document.payment.Name.value == "") { alert('Please enter a name'); return false; } //else if(isNaN(document.payment.CreditCard.value) || document.payment.CreditCard.length !== 10) //{ // alert('Invalid Credit Card Number'); // return false; //} else if (document.payment.Adress.value == "") { alert('Please enter your adress.'); return false; } else if (document.payment.State.selectedIndex == 0) { alert('Please select a state'); return false; } return true; } </script> </HEAD> <BODY> <TITLE>Check Out</TITLE> <script> var html = ""; html += '<TABLE align="center"><tr><td><img src = "images/checkOutTitle.png" align="center" style="border:none" /></td></tr></TABLE>'; html += '<TABLE align = "center" border="2" cellpadding="2" cellspacing="2" width="80%">' html += '<form id = "orderForm" name = "orderForm" method = POST action="javascript:void(0)">'; html += '<tr>'; html += '<th>Product</th><th>Quantity</th><th>Price</th><th>Sub Total</th>'; html += '</tr>'; for (var i=0; i<LaptopListPurchase.length;i=i+2) { html += '<tr><td>' + LaptopListPurchase[i] + '</td>'; html += '<td><select NAME="quantity' + i/2 + '" onChange="calculateTotalPurchaseLaptop(this.form)">'; html += '<OPTION VALUE="0">0</OPTION><OPTION VALUE="1">1</OPTION><OPTION VALUE="2">2</OPTION>'; html += '<OPTION VALUE="3">3</OPTION><OPTION VALUE="4">4</OPTION><OPTION VALUE="5">5</OPTION>'; html += '</select></td>'; html += '<td>$<input type="text" name="price' + i/2 + '" size=5 value="' + LaptopListPurchase[i+1] + '" readonly></td>'; html += '<td>$<input type="text" name="subTotal' + i/2 + '" size=5 value="0.00" readonly></td>'; html += '</tr>'; } html += '<tr>'; html += '<td></td>'; html += '<td></td>'; html += '<td></td>'; html += '<td>$<input type=TEXT name="laptopTotal" value="" readonly size=7></td></tr>'; html += '</form>'; html += '</table>'; document.write(html); // Update the quantities // var quantityLaptop; for (var i=0; i<LaptopList.length/2;i++) { // Get the quantity of each type of Laptop // quantityLaptop = getCookie("Laptop" + i); document.orderForm.elements("quantity"+i).value = quantityLaptop; } // Update the totals // calculateTotalPurchaseLaptop(document.orderForm) var html = ""; html += '<TABLE align = "center" border="2" cellpadding="2" cellspacing="2" width="80%">' html += '<form id = "orderForm2" name = "orderForm2" method = POST action="javascript:void(0)">'; html += '<tr>'; html += '<th>Product</th><th>Quantity</th><th>Price</th><th>Sub Total</th>'; html += '</tr>'; for (var i=0; i<DesktopListPurchase.length;i=i+2) { html += '<tr><td>' + DesktopListPurchase[i] + '</td>'; html += '<td><select NAME="quantity' + i/2 + '" onChange="calculateTotalPurchaseDesktop(this.form)">'; html += '<OPTION VALUE="0">0</OPTION><OPTION VALUE="1">1</OPTION><OPTION VALUE="2">2</OPTION>'; html += '<OPTION VALUE="3">3</OPTION><OPTION VALUE="4">4</OPTION><OPTION VALUE="5">5</OPTION>'; html += '</select></td>'; html += '<td>$<input type="text" name="price' + i/2 + '" size=5 value="' + DesktopListPurchase[i+1] + '" readonly></td>'; html += '<td>$<input type="text" name="subTotal' + i/2 + '" size=5 value="0.00" readonly></td>'; html += '</tr>'; } html += '<tr>'; html += '<td></td>'; html += '<td></td>'; html += '<td></td>'; html += '<td>$<input type=TEXT name="desktopTotal" value="0.00" readonly size=7></td></tr>'; html += '<td></td>'; html += '<td></td>'; html += '<td align = "center"><b>Grand Total</b></td>'; html += '<td>$<input type=TEXT name="grandTotal" value="0.00" readonly size=7></td></tr>'; html += '</form>'; html += '</table>'; document.write(html); // Update the quantities // var quantityDesktop; for (var i=0; i<DesktopList.length/2;i++) { // Get the quantity of each type of Desktop // quantityDesktop = getCookie("Desktop" + i); document.orderForm2.elements("quantity"+i).value = quantityDesktop; } // Update the totals // calculateTotalPurchaseDesktop(document.orderForm2) </script> <table align = 'center'> <tr> <td><h1>Pay for your Purchase Below</h1></td> </tr> </table> <table border="1" align = 'center' > <form name="payment" method="post"> <tr> <td> Name on Credit Card: <input type="text" name="Name" /><br /> Credit Card number: <input type="text" name="CreditCard" /><br /> Street Adress: <input type="text" name="Adress" /><br /> Town: <input type="text" name="Town" /><br /> State/Territory: <select NAME="State"><OPTION VALUE="Null">--</OPTION><OPTION VALUE="Australian Capital Territory">ACT</OPTION><OPTION VALUE="South Australia">SA</OPTION><OPTION VALUE="Northen Territory">NT</OPTION><OPTION VALUE="Queensland">QLD</OPTION><OPTION VALUE="Victoria">Vic</OPTION><OPTION VALUE="Western Australia">WA</OPTION><OPTION VALUE="Tasmania">Tas</OPTION></select> </td> <td> <INPUT TYPE="RADIO" NAME="Master Card" VALUE="Master Card">Master Card<BR> <INPUT TYPE="RADIO" NAME="Visa" VALUE="Visa">Visa<BR> <INPUT TYPE="RADIO" NAME="AMEX" VALUE="American Express">American Express<BR> </td> </tr> <tr> <td></td> <td><input type="submit" value="Submit" onclick="return checkform()"></td> </tr> </table> </BODY> </HTML>[ /quote] Site in question: www.yourvancouvermortgagebroker.ca/apply On the 3rd step of this form, I want to add a "SKIP" button that will send the user to the 5th step. No clue how to do this, as someone else helped me code. Thank You! Relevant code javascript file: Code: //step 3 $('#submit_third').click(function(){ //remove classes $('#third_step input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var fields = $('#third_step input[type=text]'); var error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='cemail' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(!error) { //update progress bar $('#progress_text').html('60% Complete'); $('#progress').css('width','204px'); //slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown(); } else return false; }); //step 4 $('#submit_fourth').click(function(){ //remove classes $('#fourth_step input').removeClass('error').removeClass('valid'); var fields = $('#fourth_step input[type=text]'); var error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<1 || value==field_values[$(this).attr('id')]) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(!error) { //update progress bar $('#progress_text').html('80% Complete'); $('#progress').css('width','272px'); //slide steps $('#fourth_step').slideUp(); $('#fifth_step').slideDown(); } }); // step 5 $('#submit_fifth').click(function(){ //remove classes $('#fifth_step input').removeClass('error').removeClass('valid'); I need to figure out the on page button code, what I need to add to the javascript file AND what I need to add in the CSS. (css is here) Thank you SO much to whoever can help. 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'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); } } } 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> |