JavaScript - Loop Validation & Query Issues
Hello,
Im still new to JS/Ajax/PHP and Im creating a filter(html checkbox form) that will call a single query that will filter unwanted items.. This query contains a INNER JOIN, AND and ON conditions. I have also created a simple javascript loop to scan the form for checked values.. but im having trouble connecting the dots.. Im not certain how to make each checked value trigger individual parts of the query.. Heres what I have: Loop: Code: function sendInfo(form) { var filterList = ""; for( var i =0; i < form.elements.length; i++ ) { if( form.elements[i].type = 'checkbox' ) { if( form.elements[i].checked == true ) { filterList += form.elements[i].value + ','; } } } alert("The filter list is " + filterList); } HTML FORM: Code: <form name="filterForm" id="filterForm"> <input type="checkbox" name="red" value="red" id="red"> RED <input type="checkbox" name="blue" value="blue" id="blue"> BLUE <input type="checkbox" name="green" value="green" id="green"> GREEN <input type="submit" name="submit" value="click" onClick="sendInfo(document.filterForm)"> </form> PHP/Mysql QUERYused to filter results) Code: $submitFilter= isset($_POST['submit']); if($submitFilter) { //checks for submitted form //connect to database //select database $filterQuery= mysql_query("SELECT * FROM table_1 INNER JOIN table_2 ON table_1.color_Id=table_2.color_Id WHERE table_2.color_Category <> 'red' AND table_2.color_Type <> 'red' AND table_2.color_Category <> 'blue' AND table_2.color_Type <> 'blue' AND table_2.color_Category <> 'green' AND table_2.color_Type <> 'green' As you can see I have joined two tables and want to exclude any from table_1 where the color is red.. how can I request this action from the loop once a check box has been checked??? like I said im new so if this looks wrong/confusing feel free to be brutal !! I have searched the forums and Iv been close to finding an example/post but nothing solid.. I think I mayb using the wrong terminology/descriptions in my searches to find the correct results bcuz I feel like im circling the block to no end.. PLEASE HELP or POINT ME IN THE RIGHT DIRECTION!!!!! THANKS IN ADVANCE! Similar TutorialsHello guys, I am trying to create a basic unobtrusive form validation function but I am having some issues/questions. Basically I am checking if any of the form fields have <= 3 characters, and if they do so, then I make those fields' backgrounds and borders red. Also in the empty <span> tags I insert an error message. My issues/questions a #1: So when I say if (fieldVals[i]<=3) this means that the errors should appear if the values are 1,2 or 3 characters long, right? It does not do that though, when I insert one character in any of the form fields the errors go away, but they should not, right? #2: How do I cancel the form from submitting if errors are visible and vice versa? When I use the return false when errors are visible, the code does not even run. What is going on? return true does the same. #3: When I use a submit button(type="submit") instead of just a button(type="button"), the code does not run? What am I doing wrong? NOTE: I am not trying to use this on a website, I am just trying to learn how to use unobtrusive javascript. That's why I am only checking for empty fields. If I learn how to do this first, later I will try to add email check, date check etc. (sorry for the long message) Any help would be much appreciated, thanks! THE CODE: function addEvent (eventObj, event, codeToEexcute) { if (eventObj.addEventListener) { eventObj.addEventListener(event, codeToEexcute, false ); } else if (eventObj.attachEvent) { // If IE event = "on" + event; eventObj.attachEvent(event, codeToEexcute); } } function cancelEvent(event) { if (event.preventDefault) { event.preventDefault(); event.stopPropagation(); } else { event.returnValue = false; event.cancelBubble = true; } } addEvent(window, 'load', pageEvents); function pageEvents () { if (!document.getElementById || !document.createTextNode) {return;} var send = document.getElementById('send'); //<input type="button" id="send" value="Contact Us" /> if (!send) {return;} addEvent(send, 'click', validate); } function validate () { var name = document.getElementById('name'); //<input type="text" name="name" id="name" value="" /> var lastName = document.getElementById('lastName'); //<input type="text" name="lastName" id="lastName" value="" /> var email = document.getElementById('email'); //<input type="text" name="email" id="email" value="" /> var subject = document.getElementById('subject'); //<input type="text" name="subject" id="subject" value="" /> var message = document.getElementById('message'); //<textarea name="message" id="message" value=""></textarea> var fields = [name, lastName, email, subject, message]; var fieldVals = [name.value, lastName.value, email.value, subject.value, message.value]; for (var i = 0; i<fieldVals.length; i++) { var contactForm = document.getElementById('contactForm'); //<form> tag var errs = contactForm.getElementsByTagName('span'); //one empty <span> tag next to each form field if (fieldVals[i]<=3) { //BUG HE it still validates with 3 or less character but it should not, right? fields[i].style.background = "#FFCCCC"; fields[i].style.borderColor = "red"; errs[i].innerHTML ="Please enter a correct value"; //by using 'i' I get the same index for the <span> tags //if I insert a "return false" here, the code above does not run. //how do I make the form not to submit when the code above is executed? } else { fields[i].style.background = "none"; fields[i].style.borderColor = "#cecece"; errs[i].innerHTML = " "; //how do I make the form to submit? when i use "return true" the code above does not run. } } //end for loop } //end validate Hello, first off, let me just say that I'm very happy to be apart of this community. It seems like this may be my new home away from home. Now, I'm a beginner with JavaScript and I'm working on a forum validation but I have a few questions. First off, here's the code I'm working on: Essentially the code below checks every field with the class "req" for input, and it also validates the email address but I'm not sure how exactly.. Could someone explain the condition for the if statement? I am really lost, especially with the random "+2's" and "x.length". What is x? it was never defined? and what is with the +2's? what are they adding onto? Thanks. Here's the code too: Code: function alertme(){ for(var i = 1;i < myform.elements.length;i++){ if(myform.elements[i].className == "req" && myform.elements[1].value.length == 0) { alert("Please fill in all required fields"); return false; } } var email = document.getElementById('email').value; var atpos = email.indexOf('@'); var dotpos = email.lastIndexOf('.'); if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= x.length){ alert("Not a valid email") false; } } Any help is appreciated, thanks a lot guys. HI All, i have a form with 5 date fields, and i need to validate these fields against each other and prevent two date fields from future dates. I have used EPOCH calendar control on my page and set all date fields as read only. The calendar function is called on page load event. I have written a function to compare my dates (comparedates()) and called this function into another function (validateform(this)) which is triggered when the form is submitted. The validateform function first checks for null values and then calls comparedates function. When i test the form, the validate form works well and the form won't submit if there are any missing details, however when it executes the comparedates() function, this is what happens: in FireFox: alerts are popping up, but the page is submitted anyway in IE8 : alerts do not pop up and the page is submitted in both browsers i don't see any javascript error. here is the code i'm using in the page, apart from validateform and compare dates, i have a function to check email and another function to disable/enable text field upon a specific selection from a drop down. These two functions work perfectly, i just included them in the code just to see if it is at all affecting my comparedate() function. please let me know if you would like to also see EPOCH calendar code. Thank you for your help Maryam Code: function getToday() { var date = new Date(); var mm = zeroPadValue(date.getMonth() + 1); var dd = zeroPadValue(date.getDate()); var yyyy = date.getFullYear(); var result = yyyy + "-" + mm + "-" + dd; return result; } function zeroPadValue(value) { if (value < 10) { value = "0" + value; } return value; } function validateForm(form) { var sysDate = new getToday(); var obj=document.createform.nationality; for(var i=0; i < form.elements.length; i++){ if(form.elements[i].value.length == 0 && form.elements[i].name != "submit" && form.elements[i].name !="qualification" && form.elements[i].name !="gender" && form.elements[i].name !="marital" && form.elements[i].name !="cbirth" && form.elements[i].name !="citybirth" && form.elements[i].name !="email" && form.elements[i].name !="pspace" && form.elements[i].name !="paidby" && form.elements[i].name !="visano" && form.elements[i].name !="difcsponsored" && form.elements[i].name !="vissuedate" && form.elements[i].name !="vexpirydate" && form.elements[i].name !="compreg"){ alert('No value entered in '+form.elements[i].title+'.'); form.elements[i].focus(); return false; } } comparedates(); return true; } function comparedates() { var form = document.forms[0]; var curr = new Date(getToday()); var getdob = new Date(document.createform.dob.value); var getpi = new Date(document.createform.pissue.value); var getpe = new Date(document.createform.pexpiry.value); for(var i=0; i < form.elements.length; i++) { if(form.elements[i].name =="dob") { if(getdob > curr) { alert(form.elements[i].title + ' cannot be greater than today\'\s date.'); form.elements[i].focus(); return false; } } if(form.elements[i].name=="pissue") { if(getpi > curr ) { alert(form.elements[i].title+' cannot be greater than today\'\s date.'); form.elements[i].focus(); return false; } if(getpi < getdob) { alert(form.elements[i].title+' cannot be smaller than ' + document.createform.dob.title + '.'); form.elements[i].focus(); return false; } } if(form.elements[i].name=="pexpiry"){ if(getpe < getpi) { alert(form.elements[i].title+' cannot be smaller than ' + document.createform.pissue.title +'.'); form.elements[i].focus(); return false; } if( getpe < getdob) { alert(form.elements[i].title+' cannot be smaller than '+ document.createform.dob.title+'.'); form.elements[i].focus(); return false; } } } } function disableFields(obj){ if(obj.options[obj.selectedIndex].value=="BH" || obj.options[obj.selectedIndex].value=="KW" || obj.options[obj.selectedIndex].value=="OM" || obj.options[obj.selectedIndex].value=="QA" || obj.options[obj.selectedIndex].value=="SA" || obj.options[obj.selectedIndex].value=="AE"){ // alert('true'); document.createform.visano.disabled=true; document.createform.difcsponsored.disabled=true; document.createform.vissuedate.disabled=true; document.createform.vexpirydate.disabled=true; } else { document.createform.visano.disabled=false; document.createform.difcsponsored.disabled=false; document.createform.vissuedate.disabled=false; document.createform.vexpirydate.disabled=false; } } function validateEmail(myemail){ var AtPos = myemail.value.indexOf("@"); var StopPos = myemail.value.lastIndexOf("."); var Message = ""; //var getemail = document.getElementById("txtemail"); if (myemail.value.length !=0){ if (AtPos == -1 || StopPos == -1 || StopPos < AtPos || StopPos - AtPos == 1) { Message = "Not a valid email address"; alert (Message); //myemail.focus(); setTimeout('document.getElementById(\'email\').focus();document.getElementById(\'email\').select();',0); //return false; } else { return true; } } } function callall(){ getCal(); // comparedates(); } I am new here, and having massive difficulties with JavaScript, so like everything else I'm interested in, there's an awesome forum available so here I am. I have been browsing the site all night, checking stickies, searching related issues, etc but still having trouble. I am creating a pizza order form. Yes I see that there are previous issues with Pizza order forms, but they did not help. I've got issues with validation, and my test code does not respond at all when I click the submit button. What am I doing wrong? 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>Final Test 2</title> <script type="text/javascript"> function crust_form() { if ( document.crust_form.crust.selectedIndex == false ) { alert ( "Please select a Crust type." ); return false; } else if ( document.crust_form.crust.selectedIndex == deep ) { alert ( "You selected Deep Dish Pizza."); return true; } else if ( document.crust_form.crust.selectedIndex == thin ) { alert ( "You selected Thin Crust Pizza."); return true; } else if ( document.crust_form.crust.selectedIndex == parmesagn ) { alert ( "You selected Parmesagn Cheese Crust Pizza."); return true; } else if ( document.crust_form.crust.selectedIndex == sourdough ) { alert ( "You selected Sourdough Crust Pizza."); return true; } } </script> </head> <body> <form action="" onsubmit="return crust();" name="crust_form" method="post"> <select name="crust"> <option selected value="false">Select Crust Type</option> <option value="deep">Deep Dish</option> <option value="thin">Thin Crust</option> <option value="Parmesagn">Parmesagn Cheese</option> <option value="sourdough">Sourdough</option> </select> <input type="submit" value="Submit"> </form> </body> </html> Hi guys, Great site by the way =). Basically if you view http://debtclock.co.uk/contact and click the form submit before inputting any details in the boxes you will see that the boxes highlight red to indicate there are some fields missing. Everything works fine, but if you view it on I.E 8 you can see that the red fill doesnt appear, only the text above it saying there are errors. Anyway I hope someone can get back to me with an idea, I am sat here in the office pulling my hair out not having an idea what it could be ><><>< Code: function ChangeElementSize(objName,ToWidth,ToHeight,Speed) { objId=document.getElementById(objName); CurWidth=parseInt(objId.style.width); CurHeight=parseInt(objId.style.height); if(CurWidth!=ToWidth) {objId.style.width=GetValueChange(CurWidth,ToWidth)+"px";} if(CurHeight!=ToHeight) {objId.style.height=GetValueChange(CurHeight,ToHeight)+"px";} if(CurWidth!=ToWidth || CurHeight!=ToHeight) { TimeoutCmd="ChangeElementSize(\""+objName+"\","+ToWidth+","+ToHeight+","+Speed+");"; setTimeout(TimeoutCmd,Speed); } } function GetValueChange(CurrentValue,ToValue) { ValueDiff=ToValue-CurrentValue; if(Math.abs(ValueDiff)!=1) {CurrentValue=CurrentValue+Math.round(ValueDiff/2);} else {CurrentValue=CurrentValue+ValueDiff;} return CurrentValue; } <div id="ChangeSizeDiv" style="position:absolute;left:0px;top:0px;width:200px;height:40px;border:5px solid green;overflow:hidden" onmouseover='ChangeElementSize("ChangeSizeDiv",500,500,40);' onclick='ChangeElementSize("ChangeSizeDiv",200,40,40);'> Hover to resize me ... </div> This is working, but with a snag ... If you run it, and hover over the div, the box grows. If you click it, it shrinks. Good, but if you hover and click fast enough it puts the box in a timeout(x2) loop. One timeout is shrinking the box, while the other is making it larger, thus competing, and neither can do its job. How can I fix this? If possible, I'd like to be able to terminate any current timeout processes, then start the new one, but I haven't figured out how to pass the timeout ID back so that it can be cancelled. 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'> function myForm(){ // Make quick references to our fields var fname = document.getElementById('fname'); var lname = document.getElementById('lname'); var address = document.getElementById('address'); var city = document.getElementById('city'); var state = document.getElementById('state'); var zcode = document.getElementById('zcode'); var email = document.getElementById('email'); // 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(isAlphanumeric(address, "Numbers and Letters Only for Address")){ if(isAlphabet(city, "Please enter only letters for your city name")){ if(madeSelection(state, "Please Choose a State")){ if(isNumeric(zcode, "Please enter a valid zip code")){ if(emailValidator(email, "Please enter a valid email address")){ return true; } } } } } } } return false; } function formChoice(elem, helperMsg){ if(elem.fname, elem.lname, elem.address, elem.city, elem.state, elem.zcode == 0 || elem.email == 0){ return true; }else{ alert(helperMsg); elem.focus(); return flase; } } function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z\s]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } </script> </head> <body> <p>My Form.</p> <form action="conformation.html" target="_self" onsubmit="return myForm()"> <fieldset> <legend>Name</legend> First Name: <input type="text" id="fname" value="" /> <br /> Last Name: <input type="text" id="lname" value="" /> <br /> </fieldset> <br /> <fieldset> <legend>Address</legend> Address: <input type="text" id="address" value="" /> <br /> City: <input type="text" id="city" value="" /> <br /> State: <select id="state"> <option>Please Choose</option> <option>AL</option> <option>AK</option> <option>AZ</option> <option>AR</option> <option>CA</option> <option>CO</option> <option>CT</option> <option>DE</option> <option>FL</option> <option>GA</option> <option>HI</option> <option>ID</option> <option>IL</option> <option>IN</option> <option>IA</option> <option>KS</option> <option>KY</option> <option>LA</option> <option>ME</option> <option>MD</option> <option>MA</option> <option>MI</option> <option>MN</option> <option>MS</option> <option>MO</option> <option>MT</option> <option>NE</option> <option>NV</option> <option>NH</option> <option>NJ</option> <option>NM</option> <option>NY</option> <option>NC</option> <option>ND</option> <option>OH</option> <option>OK</option> <option>OR</option> <option>PA</option> <option>RI</option> <option>SC</option> <option>SD</option> <option>TN</option> <option>TX</option> <option>UT</option> <option>VT</option> <option>VA</option> <option>WA</option> <option>WV</option> <option>WI</option> <option>WY</option> </select> <br /> Zip Code: <input type="text" id="zcode" value="" /> <br /> </fieldset> <br /> <br /> <fieldset> <legend>E-mail Address</legend> E-mail Address: <input type="text" id="email" value="" /> <br /> </fieldset> <input type="submit" value="Submit" /> </form> </body> </html> Hello Everyone - I am trying to make a form that requires a user to either enter in their mailing address and or e-mail or both. For example, if somebody only enters in their e-mail address the form would validate correctly and send the validation information to a conformation page. Or, the other s scenario would be they entered their mailing address information but left the e-mail field blank, the form would validate and confirm the form information on a conformation page. Or the last scenario would be that all fields were filled out, which then wouldn't be an issue(my form does this now). What I have done was made a custom function, which is in the code above on line, 39 and then have it called on an onsubmit button but that wasn't working. Code he Code: function formChoice(elem, helperMsg){ if(elem.fname, elem.lname, elem.address, elem.city, elem.state, elem.zcode == 0 || elem.email == 0){ return true; }else{ alert(helperMsg); elem.focus(); return flase; } } The other thing I tried to do was making the if on line 25 an else if else and or just an else. I understand with an else if the condition are not met than the if statement moves on to the else and if that isn't met then both statements are false and the form will not submit, but both else if else, and else doesn't work at line 25. I tried moving the line 25 e-mail line down past the brackets and that didn't work. I have read many books and have visited many sites to try on my own to learn how to do this, and I think I am not understanding some basic concepts, and I would be tickled if somebody could look at my code and look at my problem and see what knowledge I am missing and how to fix my problem. Thanks. I have a simple validation script. The first line of the validation is: function Validate() { if (document.form.name.value == '') { the id of my form is form, so my query is will this validation work, as it does not have a name but it has an id. Should I change the name (above) to id? Hello all, I have a multistep jquery form that validates user input and then should send me an email. Problem is, right now, I can only get it to validate the first page, then it sends the email before the rest of the pages are viewed. I'm just trying to delay the submission of the form until the "submit_fourth" button is pressed. I've got $25 via paypal for the one who sticks with this one for long enough to come up with a workable solution. Here is my code... I know it's a lot, but I wasn't sure how much would be helpful. HTML code is in the second post in this thread (it was just too much to fit in one go). Cheers! -Dave The Javascript: Code: $(function validateForm(){ //original field values var field_values = { //id : value 'name' : 'your name', 'email' : 'email', 'phone' : '(555) 123-4567', 'other' : 'other', 'detail' : 'project overview' }; //inputfocus $('input#name').inputfocus({ value: field_values['name'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('input#phone').inputfocus({ value: field_values['phone'] }); $('input#other').inputfocus({ value: field_values['other'] }); $('input#detail').inputfocus({ value: field_values['detail'] }); //reset progress bar $('#progress').css('width','0'); $('#progress_text').html('0% Complete'); //first_step $('form').submit(function(){ }); $('#submit_first').click(function(){ //remove classes $('#first_step input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields1 = $('#first_step input[type=text]'); var error = 0; fields1.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#first_step').slideUp(); $('#second_step').slideDown(); } else return false; }); $('#back_second').click(function(){ //update progress bar $('#progress_text').html('0% Complete'); $('#progress').css('width','0px'); //slide steps $('#second_step').slideUp(); $('#first_step').slideDown(); }); $('#submit_second').click(function(){ //remove classes $('#second_step input').removeClass('error').removeClass('valid'); var fields2 = $('#second_step input[textarea]'); var error = 0; fields2.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#second_step').slideUp(); $('#third_step').slideDown(); } else return false; }); $('#back_third').click(function(){ //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#third_step').slideUp(); $('#second_step').slideDown(); }); $('#submit_third').click(function(){ //update progress bar $('#progress_text').html('75% Complete'); $('#progress').css('width','255px'); //prepare the fourth step var fields3 = new Array( $('#time').val(), $('#budget').val() ); var fields2half = new Array( $('#detail').val() ); var fields2 = new Array( $('#other').val(), $('#pages').val() ); var fields1 = new Array( $('#name').val(), $('#email').val(), $('#phone').val(), $('#contact').val(), $('#url').val() ); var tr = $('#fourth_step tr'); tr.each(function(){ //alert( fields[$(this).index()] ) $(this).children('.1 td:nth-child(2)').html(fields1[$(this).index()]); $(this).children('.2 td:nth-child(2)').html(fields2[$(this).index()]); $(this).children('.2half td:nth-child(2)').html(fields2half[$(this).index()]); $(this).children('.3 td:nth-child(2)').html(fields3[$(this).index()]); }); //slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown(); }); $('#back_fourth').click(function(){ //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#fourth_step').slideUp(); $('#third_step').slideDown(); }); $('#submit_fourth').click(function(){ //send information to server //update progress bar $('#progress_text').html('100% Complete'); $('#progress').css('width','339px'); //slide steps $('#fifth_step').slideUp(); $('#fourth_step').slideDown(); if(error <= 0) { return true } else{ return false } }); }); Hi, I have a working contact form with 3 of the fields requiring validation and they work well. I have added extra fields to the form (StatusClass, Project, CameFrom). These 3 fields return fine but I need to validated them. My problem is that the new fields don't show in the behaviours/validate panel even though they are within the form tag. Can anyone give me any help and advice as to how to accomplish this? Many thanks Code below.... Code: <script type="text/JavaScript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } //--> </script > Code: <form action="contact_us.asp" method="post" name="contact" target="_parent" class="contentText" id="contact" onsubmit="MM_validateForm('FullName','','R','Telephone','','RisNum','Email','','RisEmail');return document.MM_returnValue"> <table width="100%" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="54%" class="subHeader">Full Name* </td> <td width="46%" class="subHeader"><input name="FullName" type="text" id="FullName" /></td> </tr> <tr> <td class="subHeader">Company Name </td> <td class="subHeader"><input name="CompanyName" type="text" id="CompanyName" /></td> </tr> <tr> <td class="subHeader">Address</td> <td class="subHeader"><input name="Address1" type="text" id="Address1" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address2" type="text" id="Address2" /></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Address3" type="text" id="Address3" /></td> </tr> <tr> <td class="subHeader">Postcode</td> <td class="subHeader"><input name="Postcode" type="text" id="Postcode" /></td> </tr> <tr> <td class="subHeader">Telephone Number* </td> <td class="subHeader"><input name="Telephone" type="text" id="Telephone" /></td> </tr> <tr> <td class="subHeader">Mobile Number </td> <td class="subHeader"><input name="Mobile" type="text" id="Mobile" /></td> </tr> <tr> <td height="25" class="subHeader">Email Address* </td> <td class="subHeader"><input name="Email" type="text" id="Email" /></td> </tr> <tr> <td height="30" class="subHeader">Status*</td> <td class="subHeader"><select name="StatusClass" id="StatusClass"> <option selected="selected">Please Choose</option> <option>Architect</option> <option>Interior Designer</option> <option>Private Client</option> <option>Student</option> <option>Trade Enquiry</option> </select> </td> </tr> <tr> <td height="23" class="subHeader">Project*</td> <td class="subHeader"><select name="Project" size="1" id="Project"> <option selected="selected">Please Choose</option> <option>Planning Stages</option> <option>New Build</option> <option>Refurbishment</option> <option>Barn Conversion</option> <option>No project - information only</option> </select> </td> </tr> <tr> <td height="37" class="subHeader">How did you hear about us?*</td> <td class="subHeader"><select name="CameFrom" size="1" id="CameFrom"> <option selected="selected">Please Choose</option> <option>Web Search</option> <option>Grand Designs</option> <option>Living Etc</option> <option>Home Building & Renovation</option> <option>Architect</option> <option>Friend/Family</option> <option>Magazine/Editorial</option> <option>Newspaper Article</option> <option>Trade Show/Exhibition</option> <option>Other</option> </select></td> </tr> <tr> <td height="24" class="subHeader">Brochure Request </td> <td class="subHeader"><input name="Brochure" type="checkbox" id="Brochure" value="checkbox" /></td> </tr> <tr> <td class="subHeader">Message</td> <td class="subHeader"><span class="style4"> <textarea name="Message" id="Message"></textarea> </span></td> </tr> <tr> <td class="subHeader"> </td> <td class="subHeader"><input name="Submit" type="submit" value="Submit" /></td> </tr> <tr> <td colspan="2" class="subHeader"><em>* Required fields</em></td> </tr> </table> </form> Hey all. I have a simple validation I need to do. I need to just make sure that a Checkbox is checked, and that a Text field has content. Sounds simple but I cannot find any thing that has a check and a text field. Here what I have. Can I modify this script to do this? A Checkbox MUST be checked and Text field MUST be filled out. This currently does the text field fine, but no Checkbox obviously. How can I add a checkbox validation to this? Thats it. Any help is appreciated. Code: <script type="text/javascript"> var textFields = ["digsig"]; function validateForm( ) { var oops = ""; // must initialize this! var form = document.sig; for ( var t = 0; t < textFields.length; ++t ) { var field = form[textFields[t]]; var value = field.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim the input if ( value.length < 1 ) { oops += "You MUST enter your Digital Signature"; } } if ( oops != "" ) { alert("ERROR:" + oops); return false; } } } </script> Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. 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! Hello... Thanks for reading... I am getting an undefined error when i try to get a value from this array in the interior loop... Code: // This is the array I am trying to access AuditTable [0] = ["Visio Modifed date","Word Modified Date","User Status","User Comment","Last Audit","Audit Status","Audit Comment"] AuditTable [1] = ["11/23/2009 8:52:18 AM","missing","OK","user comment number 1","1/1/2009","ok","audit comment number 1"] AuditTable [2] = ["11/24/2009 12:21:19 AM","missing","Out of Date","Changes from 2008 not implemented","1/2/2009","Out of Date","needs update"] AuditTable [3] = ["11/22/2009 9:24:42 PM","missing","Incomplete","Document doesnt cover all possibilities","1/3/2009","Inadequate","needs update"] I have hard coded values and had success such as: Code: data = AuditTable[1][0] But when I put the vars associated with the loop in I get an undefined error - AuditTable[i] is undefined: Code: // produces error data = AuditTable[i][j] //Works but retrieves wrong data data = AuditTable[j][i] //Works but retrieves wrong data data = AuditTable[1][i] //Works but retrieves wrong data data = AuditTable[j][2] I must be trying to access the array incorrectly or something... I have defined all the vars, and tried many combinations, alerted the values of both vars so I can prove it is not a scope issue... Am I missing something obvious? Thanks much... Code: var reportArray=new Array(); var reportData, title, subTitle, data; for(i in parmarray)// loop thru AuditTable array and get values { title = '<div style="font-family:verdana; font-size:14px; font-weight:bold; margin:25px 0px 5px 30px">'; title += namearray[i][0]; title += '</div>'; reportArray.push(title);//Take compiled variable value and put it into array for(j=0; j < AuditTable[0].length; j++)// loop thru AuditTable array and get values { subTitle = AuditTable[0][j];//points to first row of AuditTable where the labels are data = AuditTable[1][0];//points to the current row where actual data is html = i + j +'<div style="font-family:verdana; font-size:12px; color:#696969; font-weight:bold; margin-left:30px;">'; html += subTitle; html += '</div><div style="font-family:verdana; font-size:12px; color:#a9a9a9; margin-left:30px; margin-bottom:10px">'; html += data; html += "</div>"; reportArray.push(html);// put results into array } } Apologies for the confusing title. I have a scipt Code: ....style: google.maps.NavigationControlStyle.SMALL } }); <? $query = mysql_query("SELECT * FROM `family_support` WHERE 1"); while ($row = mysql_fetch_array($query)){ $org_name=$row['org_name']; $lat=$row['lat']; $long=$row['long']; $org_address=$row['org_address']; echo ("addMarker($lat, $long,'<b>$org_name</b><br/>$org_address');\n"); } ?> center = bounds.getCenter(); map.fitBounds(bounds); } </script> I want the $query to be the same as another query set up further down the page; Code: $sql_result= "SELECT * FROM family_support WHERE org_name LIKE '%$org_name%'"; if ($area != 'All') { $sql_result .=" AND area LIKE '%$area%'"; } if ($services != 'All') { $sql_result .=" AND services LIKE '%$services%'"; } if ($hardiker != 'All') { $sql_result .=" AND hardiker = '$hardiker'"; } My php is dire and help with putting these together would help me display markers on a map for all results from a search form rather than display all records within the db as is happening at present.... Also would I need to move the script from the head tag? Hi, I am doing some studying and we was to create a small loop using either the for loop, while loop or do while loop. I chose to do the for loop because it was easier to understand, but I want to know how to do the same using the while loop. Here is the for loop I have, but I cant figure out how to change to while loop. Code: for (var i = 0; i < 5; ++i) { for (var j = i; j < 5; ++j) { document.write(j + ""); } document.write("<br />"); } output is equal to: 01234 1234 234 34 4 How do you make the same using a while loop? it wont loop, as long as you enter something in the name field it will submit. also how do i stop from submitting if all fields are not filled out? any help will be appreciated) ====== function checkForm(form) { var len = form.elements.length; var h=0; for (h=0; h<=len; h++){ if ((form.elements[h].value==null) || (form.elements[h].value=="")){ alert("Please enter "+document.myForm.elements[h].name); document.myForm.elements[h].focus(); return false; } return true; } } ===body-== <FORM NAME="myForm" METHOD="post" ACTION="http://ss1.prosofttraining.com/cgi-bin/process.pl"> Name:<BR> <INPUT TYPE="text" size="30" NAME="name"><br> Email address:<BR> <INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br> Phone number:<BR> <INPUT TYPE="text" size="30" NAME="phone number"><br> Fax number:<BR> <INPUT TYPE="text" size="30" NAME="fax number"><p> <INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);"> <INPUT TYPE="reset" VALUE="Reset Form"> </FORM> on the folowing page - after the main content area - are tabs - when the page first loads - what you see is actually the first 2 tabs combined. if you click a tab and come back - it fixes itself. I can't figure out why this is happening? thanks in advance http://www.challengerlifts.com/CLFP9.shtml the javascript file is here http://www.challengerlifts.com/tabcontent.js My function below only works if all variables have values. The variable "points", "income" and "shippingPrice" are optional inputs by the user. If I leave these text fields blank the "balance" value becomes "NaN". I need some help on this function to calculate "balance" value although variable "points", "income" and "shippingPrice" are blank. Another thing is I want the output of "balance" value in 2 decimal points (money). function findBalance () { var itemPrice = <?php echo $Price; ?> var points = parseFloat(document.getElementById("text1").value); var income = parseFloat(document.getElementById("text2").value); var shippingPrice = parseFloat(document.getElementById("shippingPrice").value); var balance = document.getElementById("balance"); balance.value = itemPrice + shippingPrice - points - income; } |