JavaScript - Dynamic Form Fieldname Validation!!
Hi Guys,
is there a way to ask if the #FORM.fieldname# exist to proceed with the next one ? FYI : StartDateName22 is a dynamic generated textbox i am using the following code : <cfif not isDefined (#FORM.StartDateName22#) or #FORM.StartDateName22# or EQ "" > <cfoutput> Elemnt 2,2 is not defined </cfoutput> <cfelse> <cfoutput> Element 2,2 is defined asc: #FORM.StartDateName22# </cfoutput> </cfif> Similar TutorialsHi All, i know how to create a dynamic form or DIv ..but what i do not know is how to create a dynamic form/ or div into a previous dynamic one.. i need basically to see 5 dynamic forms / DIV in cascade where each one trigger the one coming after.. For what i need that : i have my user inserting information on the level 1. let say Copagny info 2- then he will be asked if he wants to add a sub level information ( subform) for that compagny or even many subforms at the same level .. and so on... 3- those sub level ( subforms ) can also call their respective subforms.. Any idea how to design this ? thanks Hi! I wish to know if one can dynamically validate a textbox that accepts telephone numbers. I plan to do this by: first selecting a country form a dropdown box. then validate the text box for the corresponding country selected... but do not have any idea how to do it! can you help me ? I have made a script where you can add extra fields, and next to the row is a span that automatically displays the outcome from a calculation of three fields in that row. i.e. Q x (B - A) = total. Here is the bit that does the calculation: Code: function advCalc(selected) { var result = Number(document.formmain.elements["quantity"+selected].value) * (Number(document.formmain.elements["provideamount"+selected].value) - Number(document.formmain.elements["supplyamount"+selected].value)) ; result = result.toFixed(2) ; result = addCommas(result) ; document.getElementById("total"+selected).innerHTML = result ; } The bit that adds a new row of fields is: Code: function addPart(divName){ var newdiv = document.createElement('div') ; newdiv.setAttribute('id', 'partrow' + counter) ; newdiv.setAttribute('style', 'clear:both;') ; newdiv.innerHTML = "<div style='float:left;width:40px;text-align:center;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc('" + counter + "')\" id=' quantity " + counter + "' type='text' value='1' size='1'/>\r</div>\r<div style='float:left;width:100px;text-align:left;margin:5px 0px 0px 0px;'>\r<input id='manufacturer" + counter + "'type='text' value='' size='9'/>\r</div>\r<div style='float:left;width:95px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='partnumber" + counter + "'type='text' value='' size='9'/>\r</div>\r<div style='float:left;width:80px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='supplier" + counter + "'type='text' value='' size='4'/>\r</div>\r<div style='float:left;width:100px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='type" + counter + "'type='text' value='' size='6'/>\r</div>\r<div style='float:left;width:85px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='deliverytime" + counter + "'type='text' value='' size='13'/>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 0px 0px 45px;'>\r<select id='supplyCurrency" + counter + "'>\r<option value='pound' selected='selected'>£</option><option value='dol'>$</option><option value='euro'>€</option></select>\r</div>\r<div style='float:left;width:15px;text-align:left;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc(\'" + counter + "\')\" id=' supplyamount " + counter + "'type='text' value='' size='3'/>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 0px 0px 45px;'>\r<select name='provideCurrency" + counter + "'><option value='pound' selected='selected'>£</option><option value='dol'>$</option><option value='euro'>€</option></select>\r</div>\r<div style='float:left;width:15px;text-align:left;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc(\'" + counter + "\') id=' provideamount " + counter + "' type='text' value='' size='3'/>\r</div>\r<div style='float:left;width:20px;text-align:left;margin:5px 0px 0px 45px;'>\r<strong>£</strong>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 5px 0px 0px;'><span id=' total " + counter + "'></span></div> \r" ; document.getElementById(divName).appendChild(newdiv) ; counter++ ; } The problem I am having is that it works fine for the first row which is hardcoded as e.g. id="provideamount0" etc. It isn't working for any other fields added but I can't see what is wrong 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! So I have a little calendar widget on my site, for people to choose their dates for a reservation system. They then click a 'Book Now' button which creates a dynamic url (using their start date and the number of dates) to the booking engine. The problem is, the way it accomplishes this (window.location.href=), breaks cross-domain tracking on Google Analytics. And I'm not smart enough to figure out how to do it any other way. What I'd like to do is have clicking the Book Now button change the URL in the form action within the form with ID resForm, and then submit the form. I'm hoping someone can help me edit the form so that it accomplishes this. I'd be incredibly thankful. This is what I currently have: Code: <script> jQuery(document).ready(function($) { $(".book-now").click(function() { if($('#check-in').length > 0 && $('#DepartureDate').val() != '') { var data = $('#check-in').val(); var arr = data.split('/'); var datac = $('#DepartureDate').val(); var arr2 = datac.split('/'); var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds var firstDate = new Date(arr[2],arr[0] -1,arr[1]); var secondDate = new Date(arr2[2],arr2[0] -1,arr2[1]); var diffDays = Math.round((firstDate.getTime() - secondDate.getTime())/(oneDay)); if ((diffDays) < 0) { diffDays = Math.abs(diffDays); var link = "https://res.windsurfercrs.com/bbe/page1.aspx?propertyID=13841&checkin=" + arr[0] + "/" + arr[1] + "/" + arr[2] + "&nights=" + diffDays; console.log(link); window.location.href= link; } else { alert ('Please fill in correct Check-In and Check-Out dates. The Check-In date must be before the Check-Out date.'); } } else { alert ('Please fill in a Check-In and Check-Out date, thanks!'); } }); }); </script> The form looks like this: Code: <form action="#" onSubmit="_gaq.push(['_linkByPost',this]);" method="post" id="resForm"> <input type='text' name="checkin" id="check-in" readonly="readonly" style="cursor: text" data-default="MM/DD/YYYY" class='arrivaldate'/> <input name="checkout" id="DepartureDate" readonly="readonly" style="cursor: text" data-default="MM/DD/YYYY" class='departuredate'/> <input type="button" value="BOOK NOW" class='book-now' /> </form> Reply With Quote 01-25-2015, 12:46 AM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,310 Thanks 82 Thanked 4,754 Times in 4,716 Posts Just call the _gaq() function manually. Code: _gaq.push(['_linkByPost',document.getElementBy("resForm")]) window.location.href= link; I've literally tried everything. Read 26 tutorials, interchanged code, etc. My validation functions all work. My AJAX functions work (tested manually using servlet URL's). The second servlet validates the reCaptcha form that's generated on my webpage. After the form is validated, even if everything's correct, nothing happens upon clicking submit. I even have an alert pop up if with the captcha result, just for middle-layer debugging purposes. I want to do all of my validation clientside; none serverside. However, going to be tough if I can't get my god damn form to submit. I've been puzzled by this for close to 36 hours straight. I can't see, and I'm going to get some rest and hope that there is some useful insight on my problem when I return. html form: Code: <form id="f1" name="form1" onsubmit="validate_form(this); return false;" action="register" method="post"> <table cellspacing="5" style="border: 2px solid black;"> <tr> <td valign="top"> <table cellspacing="5"> <tr> <td>*First name</td> <td align="right"><span id="valid_one"></span></td> <td><input type="text" style="width: 320px;" id="fn" name="fn" onBlur="validate_one();"></td> </tr> <tr> <td align="left">*Last name</td> <td align="right"><span id="valid_two"></span></td> <td><input type="text" style="width: 320px;" id="ln" name="ln" onBlur="validate_two();"></td> </tr> <tr> <td align="left">*Email address</td> <td align="right"><span id="result"></span></td> <td><input type="text" style="width: 320px;" id="mailfield" name="email" onBlur="startRequest();"></td> </tr> <tr> <td align="left">*Phone number</td> <td align="right"><span id="valid_three"></span></td> <td><input type="text" style="width: 320px;" id="pn" name="pn" onBlur="validate_three();"></td> </tr> <tr> <td align="left">*City/Town</td> <td align="right"><span id="valid_four"></span></td> <td><input type="text" style="width: 320px;" id="c" name="c" onBlur="validate_four();"></td> </tr> <tr> <td></td> <td></td> <td> <select name="s"> <option value="AL">Alabama <option value="AK">Alaska <option value="AZ">Arizona <option value="AR">Arkansas <option value="CA">California <option value="CO">Colorado <option value="CT">Connecticut <option value="DE">Delaware <option value="FL">Florida <option value="GA">Georgia <option value="HI">Hawaii <option value="ID">Idaho <option value="IL">Illinois <option value="IN">Indiana <option value="IA">Iowa <option value="KS">Kansas <option value="KY">Kentucky <option value="LA">Louisiana <option value="ME">Maine <option value="MD">Maryland <option value="MA">Massachusetts <option value="MI">Michigan <option value="MN">Minnesota <option value="MS">Mississippi <option value="MO">Missouri <option value="MT">Montana <option value="NE">Nebraska <option value="NV">Nevada <option value="NH">New Hampshire <option value="NJ">New Jersey <option value="NM">New Mexico <option value="NY">New York <option value="MC">North Carolina <option value="ND">North Dakota <option value="OH">Ohio <option value="OK">Oklahoma <option value="OR">Oregon <option value="PA">Pennsylvania <option value="RI">Rhode Island <option value="SC">South Carolina <option value="SD">South Dakota <option value="TN">Tennessee <option value="TX">Texas <option value="UT">Utah <option value="VT">Vermont <option value="VA">Virginia <option value="WA">Washington <option value="WV">West Virginia <option value="WI">Wisconsin <option value="WY">Wyoming </select> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td></td> <td></td> <td><span id="error"></span></td> </tr> <tr> <td valign="top">*Anti-Spam Verification</td> <td></td> <td id="reCaptcha"></td> </tr> </table> </td> <td valign="top"> <table cellspacing="5"> <tr> <td align="left">*Affiliation</td> <td align="right"><span id="valid_five"></span></td> <td><input type="text" style="width: 320px;" id="affl" name="affl" onBlur="validate_five();"></td> </tr> <tr> <td align="left">*Research Area:</td> <td align="right"><span id="valid_six"></span></td> <td><input type="text" style="width: 320px;" id="ra" name="ra" onBlur="validate_six();"></td> </tr> <tr> <td valign="top" align="left">*Research Overview</td> <td align="right"><span id="valid_seven"></span></td> <td><textarea cols="38" rows="6" id="ro" name="ro" onKeyDown="limitText(this.form.ro,this.form.countdown,500)" onKeyUp="limitText(this.form.ro,this.form.countdown,500)" onBlur="validate_seven();"></textarea></td> </tr> <tr> <td></td> <td></td> <td><font size="1">You have <input readonly type="text" name="countdown" size="1" value="500"> characters remaining.</font></td> </tr> <tr> <td align="left">*Talk Availability</td> <td></td> <td> <input type="radio" name="ta" value="In person">In person <input type="radio" name="ta" value="Online">Online <input type="radio" name="ta" value="Both" checked>Both </td> </tr> <tr> <td align="left" valign="top">Links</td> <td></td> <td> <table id="linkTable" border="0"> <td><input type="text" style="width: 320px;" name="link"></td> <td><div id="result"></div></td> </table> </td> <td align="left" valign="top"><input type="button" value="Add Link" onclick="addLink('linkTable')"></td> </tr> <tr> <td></td> <td><span style="color: red;"></span></td> </tr> </table> </td> </tr> </table> <br /> <input type="submit" id="submit" name="submit" value="Submit Form"> </form> Javascript file: Code: /* * script.js - ajax and table functions */ var xmlHttp; // global instance of XMLHttpRequest var xmlHttp2; // second for captcha functions var validAjax = new Boolean(); var validCaptcha = new Boolean(); var valid_one = new Boolean(); var valid_two = new Boolean(); var valid_three = new Boolean(); var valid_four = new Boolean(); var valid_five = new Boolean(); var valid_six = new Boolean(); var valid_seven = new Boolean(); function init() { showRecaptcha('reCaptcha'); // Separate booleans for AJAX funcs validAjax = false; validCaptcha = false; // Booleanse for fields that don't require servlet validation valid_one = false; valid_two = false; valid_three = false; valid_four = false; valid_five = false; valid_six = false; valid_seven = false; } function showRecaptcha(element) { Recaptcha.create("6Le1a8ESAAAAAGtxX0miZ2bMg0Wymltnth7IG-Mj", element, {theme: "red", callback: Recaptcha.focus_response_field}); } function validate_form() { if (valid_one && valid_two && valid_three && valid_four && validEmail) { startCaptchaRequest(); if (validCaptcha) { return true; } } else { alert("Submission contains errors. Please fill out all required fields before submitting."); return false; } } function validate_one() { if (document.getElementById("fn").value == 0) { valid_one = false; document.getElementById("valid_one").innerHTML = "No"; } else { valid_one = true; document.getElementById("valid_one").innerHTML = ""; } } function validate_two() { if (document.getElementById("ln").value == 0) { valid_two = false; document.getElementById("valid_two").innerHTML = "No"; } else { valid_two = true; document.getElementById("valid_two").innerHTML = ""; } } function validate_three() { if (document.getElementById("pn").value == 0) { valid_three = false; document.getElementById("valid_three").innerHTML = "No"; } else { valid_three = true; document.getElementById("valid_three").innerHTML = ""; } } function validate_four() { if (document.getElementById("c").value == 0) { valid_four = false; document.getElementById("valid_four").innerHTML = "No"; } else { valid_four = true; document.getElementById("valid_four").innerHTML = ""; } } function validate_five() { if (document.getElementById("affl").value == 0) { valid_five = false; document.getElementById("valid_five").innerHTML = "No"; } else { valid_five = true; document.getElementById("valid_five").innerHTML = ""; } } // //function validate_six() { // if (document.getElementById("ra").value == 0) { // valid_six = false; // document.getElementById("valid_six").innerHTML = "No"; // } // else { // valid_six = true; // document.getElementById("valid_six").innerHTML = ""; // } //} // //function validate_seven() { // if (document.getElementById("ro").value == 0) { // valid_seven = false; // document.getElementById("valid_seven").innerHTML = "No"; // } // else { // valid_seven = true; // document.getElementById("valid_seven").innerHTML = ""; // } //} function addLink(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell = row.insertCell(0); var element1 = document.createElement("input"); element1.type = "text"; element1.name = "link" + rowCount; element1.style.width = "320px"; cell.appendChild(element1); } function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } function createXmlHttpRequest() { if(window.ActiveXObject) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } } function startRequest() { createXmlHttpRequest(); var param1 = document.getElementById('mailfield').value; if (param1 == "") { validEmail = false; document.getElementById("result").innerHTML = "Blank"; } else { xmlHttp.open("GET", "http://localhost:1979/PolarSpeakers/servlet/mailCheck.do?e=" + param1, true) xmlHttp.onreadystatechange = handleStateChange; xmlHttp.send(null); } } function handleStateChange() { if(xmlHttp.readyState==4) { if(xmlHttp.status==200) { var message = xmlHttp.responseXML .getElementsByTagName("valid")[0] .childNodes[0].nodeValue; if (message == "Unregistered") { validEmail = true; document.getElementById("result").style.color = "green"; } else { validEmail = false; document.getElementById("result").style.color = "red"; } document.getElementById("result").innerHTML = message; } else { alert("Error checking e-mail address - " + xmlHttp.status + " : " + xmlHttp.statusText); } } } function createCaptchaRequest() { if(window.ActiveXObject) { xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp2=new XMLHttpRequest(); } } function startCaptchaRequest() { alert('made it to captcha requeswt'); createCaptchaRequest(); var param1 = Recaptcha.get_challenge(); var param2 = Recaptcha.get_response(); xmlHttp2.open("POST", "http://localhost:1979/PolarSpeakers/servlet/captchaCheck.do?c=" + param1 + "&r=" + param2, true) xmlHttp2.onreadystatechange = handleStateChangeCaptcha; xmlHttp2.send(null); } function handleStateChangeCaptcha() { if(xmlHttp2.readyState==4) { if(xmlHttp2.status==200) { var message = xmlHttp2.responseXML .getElementsByTagName("result")[0] .childNodes[0].nodeValue; if (message == "Valid") { alert("captcha valid"); validCaptcha = true; } else { document.getElementById("error").innerHTML = message; validCaptcha = false; } } else { alert("Error checking captcha validity - " + xmlHttp2.status + " : " + xmlHttp2.statusText); } } } Hi, I have a working contact form with 3 of the fields requiring validation and they work well. I have added extra fields to the form (StatusClass, Project, CameFrom). These 3 fields return fine but I need to validated them. My problem is that the new fields don't show in the behaviours/validate panel even though they are within the form tag. Can anyone give me any help and advice as to how to accomplish this? Many thanks Code below.... Code: <script type="text/JavaScript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } //--> </script > Code: <form action="contact_us.asp" method="post" name="contact" target="_parent" class="contentText" id="contact" onsubmit="MM_validateForm('FullName','','R','Telephone','','RisNum','Email','','RisEmail');return document.MM_returnValue"> <table width="100%" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="54%" class="subHeader">Full Name* </td> <td width="46%" class="subHeader"><input name="FullName" type="text" id="FullName" /></td> </tr> <tr> <td class="subHeader">Company Name </td> <td class="subHeader"><input name="CompanyName" type="text" id="CompanyName" /></td> </tr> <tr> <td class="subHeader">Address</td> <td class="subHeader"><input name="Address1" type="text" id="Address1" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address2" type="text" id="Address2" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address3" type="text" id="Address3" /></td> </tr> <tr> <td class="subHeader">Postcode</td> <td class="subHeader"><input name="Postcode" type="text" id="Postcode" /></td> </tr> <tr> <td class="subHeader">Telephone Number* </td> <td class="subHeader"><input name="Telephone" type="text" id="Telephone" /></td> </tr> <tr> <td class="subHeader">Mobile Number </td> <td class="subHeader"><input name="Mobile" type="text" id="Mobile" /></td> </tr> <tr> <td height="25" class="subHeader">Email Address* </td> <td class="subHeader"><input name="Email" type="text" id="Email" /></td> </tr> <tr> <td height="30" class="subHeader">Status*</td> <td class="subHeader"><select name="StatusClass" id="StatusClass"> <option selected="selected">Please Choose</option> <option>Architect</option> <option>Interior Designer</option> <option>Private Client</option> <option>Student</option> <option>Trade Enquiry</option> </select> </td> </tr> <tr> <td height="23" class="subHeader">Project*</td> <td class="subHeader"><select name="Project" size="1" id="Project"> <option selected="selected">Please Choose</option> <option>Planning Stages</option> <option>New Build</option> <option>Refurbishment</option> <option>Barn Conversion</option> <option>No project - information only</option> </select> </td> </tr> <tr> <td height="37" class="subHeader">How did you hear about us?*</td> <td class="subHeader"><select name="CameFrom" size="1" id="CameFrom"> <option selected="selected">Please Choose</option> <option>Web Search</option> <option>Grand Designs</option> <option>Living Etc</option> <option>Home Building & Renovation</option> <option>Architect</option> <option>Friend/Family</option> <option>Magazine/Editorial</option> <option>Newspaper Article</option> <option>Trade Show/Exhibition</option> <option>Other</option> </select></td> </tr> <tr> <td height="24" class="subHeader">Brochure Request </td> <td class="subHeader"><input name="Brochure" type="checkbox" id="Brochure" value="checkbox" /></td> </tr> <tr> <td class="subHeader">Message</td> <td class="subHeader"><span class="style4"> <textarea name="Message" id="Message"></textarea> </span></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Submit" type="submit" value="Submit" /></td> </tr> <tr> <td colspan="2" class="subHeader"><em>* Required fields</em></td> </tr> </table> </form> I've set up a mock registration form page so I can learn a bit about javascript's form validation. (newbie) I want to try to attempt to style the border of a form field green when the user enters the correct info into the form text field and red on all other fields if the user doesnt enter any info into them. When i test it, enter the right info into the username field, leave the others blank, and hit the submit button it styles the username field green ok but it doesnt make the next fields (password and so on) red. Could someone please explain what I am doing wrong? here is my code so far... Note: just for testing purposes I've put return false on everything so it displays a message when everythings ok. Code: .... <script type="text/javascript"> window.onload = function() { document.forms[0].username.focus(); } function validate(form) { var form = document.getElementById("reg"); var e = document.getElementById("error"); e.style.background = "red"; for(var i = 0; i < form.elements.length; i++) { var el = form.elements[i]; if(el.type == "text" || el.type == "password") { if(el.value == "") { e.innerHTML = "Please fill in all fields!"; el.style.border = "1px solid red"; el.focus(); return false; } else { el.style.border = "1px solid green"; return false; } } } var un = form.username; un.value = un.value.replace(/^\s+|\s+$/g,""); if((un.value.length < 3)|| (/[^a-z0-9\_]/gi.test(un.value))) { e.innerHTML = "Only letters,numbers and the underscore are allowed (no spaces) - 3-16 characters"; un.focus(); return false; } var pw = form.password; pw.value = pw.value.replace(/^\s+|\s+$/g,""); if((pw.value.length < 3) || (/[^a-z0-9]/gi.test(pw.value))) { e.innerHTML = "Only letters and numbers are allowed (no spaces) - 3-16 characters"; pw.focus(); return false; } e.innerHTML = "You filled in all the fields, well done!"; e.style.background = "green"; return false; } </script> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Cool Website</h1> </div> <div id="content"> <div class="padding"> <h2>Registration</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc vitae purus. Aenean viverra malesuada libero. Fusce ac quam. Donec neque. Nunc venenatis enim nec quam. Cras faucibus, justo vel accumsan aliquam, tellus dui fringilla quam, in condimentum augue lorem non tellus. Pellentesque id arcu non sem placerat iaculis. Curabitur posuere, pede vitae lacinia accumsan, enim nibh elementum orci, ut volutpat eros sapien nec sapien. Suspendisse neque arcu, ultrices commodo, pellentesque sit amet, ultricies ut, ipsum. Mauris et eros eget erat dapibus mollis. Mauris laoreet posuere odio. Nam ipsum ligula, ullamcorper eu, fringilla at, lacinia ut, augue. Nullam nunc.</p> <form id="reg" action="#" method="post" onsubmit="return validate(this)"> <div id="error"></div> <div><label for="username">Username</label></div> <div><input type="text" name="username" id="username" size="30" maxlength="16" /></div> <div><label for="password">Password</label></div> <div><input type="password" name="password" id="password" size="30" maxlength="16" /></div> <div><label for="c_password">Confirm Password</label></div> <div><input type="password" name="c_password" id="c_password" size="30" maxlength="16" /></div> <div><label for="email">Email address</label></div> <div><input type="text" name="email" id="email" size="30" maxlength="200" /></div> <div><label for="c_email">Confirm Email address</label></div> <div><input type="text" name="c_email" id="c_email" size="30" maxlength="200" /></div> <div><label for="firstname">First name</label></div> <div><input type="text" name="firstname" id="firstname" size="30" maxlength="100" /></div> <div><label for="surname">Surname</label></div> <div><input type="text" name="surname" id="surname" size="30" maxlength="100" /></div> <div><label for="gender">Gender</label></div> <div> <div><input type="radio" name="gender" id="gender" value="m" checked="checked" />Male</div> <div><input type="radio" name="gender" value="f" />Female</div> </div> <div><input type="submit" value="Register" name="submit" /></div> </form> </div> </div> <div id="footer"> <p>Copyright © 2009 My Cool Website</p> </div> </div> </body> </html> Hi guys, Been stuck for a few days with this scenario. Any help? The alert box appears on an error. But the submitting won't stop. The details are submitted and the form is processed. Any help is greatly appreciated... Code: <html> <head> <script type="text/javascript" src="email_helper/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode : "textareas", theme : "simple" }); </script> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); } function err_check(){ var email = document.getElementById('to_email').value; if(email.length==0){ alert('Please Enter Email Address'); return false; } var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } email = document.getElementById('cc_email').value; if(email.length != 0){ var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } } var answer = confirm ("Send E-Mail?"); if (!answer){ return false; } } </script> <!-- /TinyMCE --> <style type="text/css"> body, table, td, th{ background-color:#CCCCCC; font-family: Arial; font-size:14px; } .que{ font-weight:bold; } </style> </head> <body> <form method="post" enctype="multipart/form-data"> <?php include 'library/database.php'; include 'library/opendb.php'; $query = mysql_query("SELECT email,contact,mobile FROM users WHERE user_id='$uid'") or die(mysql_error()); $row = mysql_fetch_row($query); $from_email = $row[0]; $from_person = $row[1]; $from_mobile = $row[2]; $query = mysql_query("SELECT customer_id FROM campaign_summary WHERE camp_id='$camp_id'") or die(mysql_error()); $row = mysql_fetch_row($query); $cusid = $row[0]; $query = mysql_query("SELECT email FROM client_info WHERE comp_id='$cusid'") or die(mysql_error()); $row = mysql_fetch_row($query); $toer = $row[0]; include 'library/closedb.php'; ?> <table width="100%" border="0"> <tr><td rowspan="4"><input type="submit" name="send_email" id="send_email" style="height:50px; width:100px;" value="SEND" onClick="return err_check();" /></td><td><span class="que">From : </span></td><td colspan="3"><?php echo $from_email; ?><input type="hidden" name="from_mail" id="from_mail" /><input type="hidden" name="camp_id" id="camp_id" value="<?php echo $camp_id;?>"/></td></tr> <tr><td><span class="que">To : </span></td><td colspan="3"><input name="to_email" id="to_email" style="width:250px;" value="<?php echo $toer;?>"/></td></tr> <tr><td><span class="que">CC : </span></td><td colspan="3"><input name="cc_email" id="cc_email" style="width:250px;"/></td></tr> <tr><td><span class="que">Subject : </span></td><td colspan="3"><input style="width:300px;" name="subject" id="subject" /></td></tr> <tr><td rowspan="1" colspan="2"> </td><td><input type="checkbox" name="ori_pdf" id="ori_pdf" checked /> PDF Quotation</td><td> </td><td> </td></tr><tr><td colspan="2"><span class="que">Credit Application</span></td><td><input type="checkbox" name="corporate" id="corporate"/>Corporate</td><td><input type="checkbox" name="individual" id="individual" />Individual</td><td><input type="checkbox" name="cash" id="cash" />Cash Account</td> </tr> <tr> <td colspan="2" rowspan="3"></td><td><input type="checkbox" name="tabloid" id="tabloid" />Tabloid Example</td> <td><input type="checkbox" name="broadsheet" id="broadsheet" />Broadsheet Example</td></tr> <tr><td><input type="checkbox" name="colmt" id="colmt" />Column Sizes Tabloid</td> <td><input type="checkbox" name="colmb" id="colmb" />Column Sizes Broadsheet</td></tr> <tr><td><input type="checkbox" name="maps" id="maps" />Maps / Distribution</td><td colspan="2" align="right">External Attachments <input id="upload_file" name="upload_file" type="file"/> </td></tr> <tr><td colspan="2"><span class="que">Message :</span></td><td colspan="3"> <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 100%"> <?php echo "<br><br><br>" . $from_person . "<br>" . $from_mobile; ?> </textarea> </td></tr> </table> </form> </body> </html> Hello all, I have a multistep jquery form that validates user input and then should send me an email. Problem is, right now, I can only get it to validate the first page, then it sends the email before the rest of the pages are viewed. I'm just trying to delay the submission of the form until the "submit_fourth" button is pressed. I've got $25 via paypal for the one who sticks with this one for long enough to come up with a workable solution. Here is my code... I know it's a lot, but I wasn't sure how much would be helpful. HTML code is in the second post in this thread (it was just too much to fit in one go). Cheers! -Dave The Javascript: Code: $(function validateForm(){ //original field values var field_values = { //id : value 'name' : 'your name', 'email' : 'email', 'phone' : '(555) 123-4567', 'other' : 'other', 'detail' : 'project overview' }; //inputfocus $('input#name').inputfocus({ value: field_values['name'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('input#phone').inputfocus({ value: field_values['phone'] }); $('input#other').inputfocus({ value: field_values['other'] }); $('input#detail').inputfocus({ value: field_values['detail'] }); //reset progress bar $('#progress').css('width','0'); $('#progress_text').html('0% Complete'); //first_step $('form').submit(function(){ }); $('#submit_first').click(function(){ //remove classes $('#first_step input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields1 = $('#first_step input[type=text]'); var error = 0; fields1.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#first_step').slideUp(); $('#second_step').slideDown(); } else return false; }); $('#back_second').click(function(){ //update progress bar $('#progress_text').html('0% Complete'); $('#progress').css('width','0px'); //slide steps $('#second_step').slideUp(); $('#first_step').slideDown(); }); $('#submit_second').click(function(){ //remove classes $('#second_step input').removeClass('error').removeClass('valid'); var fields2 = $('#second_step input[textarea]'); var error = 0; fields2.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#second_step').slideUp(); $('#third_step').slideDown(); } else return false; }); $('#back_third').click(function(){ //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#third_step').slideUp(); $('#second_step').slideDown(); }); $('#submit_third').click(function(){ //update progress bar $('#progress_text').html('75% Complete'); $('#progress').css('width','255px'); //prepare the fourth step var fields3 = new Array( $('#time').val(), $('#budget').val() ); var fields2half = new Array( $('#detail').val() ); var fields2 = new Array( $('#other').val(), $('#pages').val() ); var fields1 = new Array( $('#name').val(), $('#email').val(), $('#phone').val(), $('#contact').val(), $('#url').val() ); var tr = $('#fourth_step tr'); tr.each(function(){ //alert( fields[$(this).index()] ) $(this).children('.1 td:nth-child(2)').html(fields1[$(this).index()]); $(this).children('.2 td:nth-child(2)').html(fields2[$(this).index()]); $(this).children('.2half td:nth-child(2)').html(fields2half[$(this).index()]); $(this).children('.3 td:nth-child(2)').html(fields3[$(this).index()]); }); //slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown(); }); $('#back_fourth').click(function(){ //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#fourth_step').slideUp(); $('#third_step').slideDown(); }); $('#submit_fourth').click(function(){ //send information to server //update progress bar $('#progress_text').html('100% Complete'); $('#progress').css('width','339px'); //slide steps $('#fifth_step').slideUp(); $('#fourth_step').slideDown(); if(error <= 0) { return true } else{ return false } }); }); 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 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> hi i got some code from another site. i modified it according to my needs. what is it doing it adds dynamic form fields by clicking "add another" link. the problem is when logged in user wants to modify his contact details he clicks on edit then gets to this modification form where all the data in his db is selected and displayed in that form fields. so the problem here is when he clicks on add another link it adds up that many fields sets that appeared currently. means if there appeared four sets of fields then clicking on add another link will add four more fields. what i want is to add only one set of fields which contains of text field and select menu. my code is here Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#btnAdd').click(function() { var num = $('.clonedInput').length; var newNum = new Number(num + 1); var newElem = $('#input' + num).clone().attr('id', 'input' + newNum); newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum); $('#input' + num).after(newElem); }); }); </script> <style> #myForm div { font-size:14px; margin-bottom: 10px; clear: left; } #myForm label { width: 125px; display: block; font-size:14px; font-weight: bold; color: #999; float: left; } #btnAdd { margin-left:130px; } </style> </head> <body> <form id="myForm" method="post" action="process.php"> <div> <label>First Name: </label><input type="text" name="fname" id="fname"><br> </div> <div> <label>Last Name: </label><input type="text" name="lname" id="lname"><br> </div> <?php $connect = mysql_connect("localhost","user","pass"); mysql_select_db("db"); $get_im = mysql_query("SELECT * FROM contactim WHERE userid='$_SESSION[userid]'"); $count = mysql_num_rows($get_im); while($get_contactim = mysql_fetch_assoc($get_im)) { $userim_db = $get_contactim['username']; $im_db = $get_contactim['im']; //echo $userim_db."<br>"; for($i = 1; $i <= $count; $i++) { ?> <div id="input1" class="clonedInput"> <label>IM Screen Names:</label> <input type="text" name="name[]" id="name1" value="<?php if($userim_db == "") { echo ""; } else { echo $userim_db; } ?>" /> <select name="screenname[]" id="screenname1"> <option value="AIM" <?php if($im_db == "AIM") { echo "SELECTED"; } ?>>AIM</option> <option value="gtalk" <?php if($im_db == "gtalk") { echo "SELECTED"; } ?>>Google Talk</option> <option value="skype" <?php if($im_db == "skype") { echo "SELECTED"; } ?>>Skype</option> <option value="windows" <?php if($im_db == "windows") { echo "SELECTED"; } ?>>Windows Live</option> <option value="yahoo" <?php if($im_db == "yahoo") { echo "SELECTED"; } ?>>Yahoo</option> </select><br /> <?php } } ?> </div> <div> <a href="#" id="btnAdd">Add another</a> </div> <input type="submit" name="submit" value="Submit"> </form> </body> </html> hi i need help in creating dynamic form using jquery. i create a form in this form i want when "add another" link is clicked then it adds one more set of fields. form is here 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>Untitled Document</title> <script type="text/javascript" src="lib/jquery-1.4.min(Production).js"></script> <script src="js/script.js" type="text/javascript"></script> <style> #form1 div { font-size:14px; margin-bottom: 10px; clear: left; } #form1 label { width: 125px; display: block; font-size:14px; font-weight: bold; color: #999; float: left; } #link { margin-left:125px; } </style> </head> <body> <form id="form1" name="form1" method="post" action=""> <div> <label>IM Screen Names:</label> <input type="text" name="textfield" id="textfield" /> <select name="select" id="select"> <option value="AIM" selected="selected">AIM</option> <option value="gtalk">Google Talk</option> <option value="skype">Skype</option> <option value="windows live">Windows Live</option> <option value="yahoo">Yahoo</option> </select><br /> <div id="link"><a href="">Add another</a></div> </div> </form> </body> </html> Is this possible? Please look at the attached image. I am trying to create a team creation page for a site I am making, however I want the user to be able to see all the names they enter before the information is passed to the .php file to send it to the MySQL table. 1. So, every time the user enters a name and presses the "add name" button the name details are stored in an Javascript array and displayed in the box below. 2. When the user presses the "save team" button the team name is passed by a simple form post and the javascript array is passed to a php array and then processed ready to be passed to the MySQL table. The problem is I don't know to do the first bit (number1). Any ideas or pointers? 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> Hello, I've used the concept from this website to build a form. http://www.enviromark.ca/english/quoteform.html Notice how the second drop down options change depending on what option is selected in the first drop down. Here's the Javascript Code: var Option1_Array = new Array("Choose a version", "1", "2"); var Option2_Array = new Array("Choose a version", "3", "4"); function program(objProgram) { var objVersion = objProgram.form.Version; var selectedArray = window[objProgram.options[objProgram.selectedIndex].value.replace(/\s/g,'') + "_Array"]; objVersion.options.length = 0; for (var i=0; i < selectedArray.length; i++) { objVersion.options[i]=new Option(selectedArray[i], selectedArray[i].replace(/->\s/g, "")); } } Here's the HTML Code: <form> <select name="Program" onChange="program(this)"> <option value="Start">Please choose a program</option> <option value=Null>---------------------------------------></option> <option value="Option1">1</option> <option value="Option2">2</option> </select> <select name="Version" onChange=""> </select> </form> Now, this code works perfectly, and does exactly what I want it to. BUT I'd like to add more fields that accomplish the same thing. For example choose option1 --> version 2 --> type 3 --> thing 5 Now, in order to do this I believe you need to generate a 'value = "a_value"' in the generated html option and select fields. That way, all you need to do is make separate functions for each level and the function can call the 'value' html attribute to handle each <select> depending on its declared value. If this is the best way (it sounds a little sketchy to me) then any help would be great. Or, if you can add on more child selection options within one function. Thanks, -Matthew Hi guys, I am able to create some of the dynamic controls but having trouble to order them in one column.. i have this view : field1 field2 field3 what i want is : field1 field2 field3 below is my code : function AddLevel2() { //var mainContainer2 = document.getElementById('mainContainer2'); var newDiv = document.createElement('div') newDiv.style.width = "560px"; newDiv.style.backgroundColor= projbgGr; newDiv.style.position = "relative"; newDiv.style.left = "245px"; var BUDDL = document.createElement('select'); // size lenght of the DDL for both IE or Firefox BUDDL.setAttribute("style","width:100px"); //firefox BUDDL.setAttribute("width","100px"); BUDDL.style.width = "100px"; BUDDL.id = 'BU' + b ; BUDDL.setAttribute('name','BU' + b); BUDDL.style.position = "relative"; BUDDL.style.left = "5px"; BUDDL.onchange=show; // filling the DDL by ITEM array Elements var i=0; for (i=0;i<=4;i++) { objOption = document.createElement('option') objOption.text = "BU" + i; //objOption.value=ITEM1[i]; BUDDL.options.add(objOption); } var j =1; var bgc = "##C8BBD0" //mauve light ; //"##D4F1B9" green light; //"##b2d47e"; //add Description Unit Description = document.createElement( 'INPUT' ); Description.id = 'D' + b ; Description.setAttribute('name','D' + b); Description.size=2; // size lenght of the Comment for both IE or Firefox Description.setAttribute("style","width:300px"); //firefox Description.setAttribute("width","300px"); Description.style.width = "300px"; Description.onblur = show; //Description.style.backgroundColor= bgc; //end Description //number of testers NumberTesters = document.createElement( 'INPUT' ); NumberTesters.id = 'T' + b; NumberTesters.setAttribute('name','T' + b ); NumberTesters.size=2; // size lenght of the Comment for both IE or Firefox NumberTesters.setAttribute("style","width:40px"); //firefox NumberTesters.setAttribute("width","40px"); NumberTesters.style.width = "40px"; NumberTesters.onblur=show; //NumberTesters.style.backgroundColor= bgc; //number of testers // Create buttons for creating and removing inputs var newAddButton = document.createElement('input'); newAddButton.type = "button"; newAddButton.value = " + "; var newDelButton = document.createElement('input'); newDelButton.type = "button"; newDelButton.value = " - "; newDelButton.style.position = "relative"; newDelButton.style.left = "7px"; // Append new text input to the newDiv newDiv.appendChild(BUDDL); newDiv.appendChild(Description); newDiv.appendChild(NumberTesters); newDiv.appendChild(newDelButton); //newDiv.appendChild(newAddButton2); //Append newDiv input to the mainContainer div mainContainer.appendChild(newDiv); //Add a handler to button for deleting the newDiv from the mainContainer newAddButton.onclick = AddLevel22; //newAddButton.onclick = AddNewRecord; //newAddButton2.onclick = AddLevel3; newDelButton.onclick = function() { var answer = confirm ("You have to delete all UATs under this BU first\n \tIs this done ?\t") if (answer) {alert ("Now you can delete it"); mainContainer.removeChild(newDiv);} else alert ("Then please check all UATs under this BU first and delete them"); } b++; document.form1.NumberOfBU.value = parseInt(b-1); //alert(document.form1.NumberOfBU.value); //AddLevel3; for (UATCounter = 1 ; UATCounter<=limit; UATCounter++) { //var newDiv = document.createElement('div') // // newDiv.style.width = "250px"; // newDiv.style.backgroundColor= projbgVi; // newDiv.style.position = "relative"; // newDiv.style.left = "350px"; var bgc = "##C8BBD0" //mauve light ; //"##D4F1B9" green light; //"##b2d47e"; newMDate = document.createElement( 'INPUT' ); newMDate.id = 'M'+ (b-1) + '_' + UATCounter ; newMDate.setAttribute('name','M'+ (b-1) + '_' + UATCounter); newMDate.setAttribute('type', 'Date'); newMDate.size=7; newMDate.style.backgroundColor= bgc; //newMDate.onfocus=Calend; // function Calend () // { // fnInitCalendar(this, this.getAttribute('id'), 'style=calendar.css,close=true'); // } newMDate.onblur = show; //Frontline Hours FLHours = document.createElement( 'INPUT' ); FLHours.id = 'FL'+ (b-1) + '_' + UATCounter ; FLHours.setAttribute('name', 'FL'+ (b-1) + '_' + UATCounter); FLHours.size=2; // size lenght of the Comment for both IE or Firefox FLHours.setAttribute("style","width:40px"); //firefox FLHours.setAttribute("width","40px"); FLHours.style.width = "40px"; //NumberTesters.style.backgroundColor= bgc; //Frontline Hours MGRHours = document.createElement( 'INPUT' ); MGRHours.id = 'MG'+ (b-1) + '_' + UATCounter ; MGRHours.setAttribute('name', 'MG'+ (b-1) + '_' + UATCounter); MGRHours.size=2; // size lenght of the Comment for both IE or Firefox MGRHours.setAttribute("style","width:40px"); //firefox MGRHours.setAttribute("width","40px"); MGRHours.style.width = "40px"; //NumberTesters.style.backgroundColor= bgc; //Frontlne Hours //Create buttons for creating and removing inputs var newAddButton = document.createElement('input'); newAddButton.type = "button"; newAddButton.value = " + "; var newDelButton = document.createElement('input'); newDelButton.type = "button"; newDelButton.value = " - "; newDelButton.style.position = "relative"; newDelButton.style.left = "7px"; //newDiv.appendChild(ProjDDL3); newDiv.appendChild(newMDate); newDiv.appendChild(FLHours); newDiv.appendChild(MGRHours); mainContainer.appendChild(newDiv); } } hello Sir/Mam i have a piece of code here that creates a dynamic form.. Code: <script type='text/javascript' language='javascript'> <!-- function createTextbox(){ var textboxtag = document.createElement("input"); textboxtag.setAttribute("name","username"); document.getElementById("form1").appendChild(textboxtag); } --> </script> <body> <div id='div1'> <button name='textbox' onclick='createTextbox()'>Textbox</button> </div> <div id='div2'> <form id='form1' action='#' method='post'> </form> </div> </body> this code sets the "name" attribute to "username" automatically.. my problem is how to set the name attribute manually by the user after the dynamic textbox is created.. just like in visual basic where after you create a form e.g button or textfield, theres a side pane where you can change attributes like name, value, etc.. tnx for the time reading my post..sorry for my poor explanation of the problem..im new in javascript and trying to learn it all by myself.. |