stublackett Posted June 3, 2008 Share Posted June 3, 2008 Hi, I'm a total JavaScript newbie, Working on an existing site which calculates the total price of each selected Adult, Child, Senior Citizen etc. It is for a coach trip and a coach trip can only run if theres 15 or more people on it, But at the moment it is allowing less than 15 to be submitted, So what I'd like to do is work out the values that have been entered, If they havent entered 15 or more then block the form from being sent, Or perhaps a pop up message stating that a coach trip needs 15 or more to run Here is the Java Code function calculate() { validkids = false; validadults = false; if(!(parseInt(document.form2['NUMBER-OF-KIDS'].value,10) > 0)) document.form2['NUMBER-OF-KIDS'].value = 0 if(!(parseInt(document.form2['NUMBER-OF-SPECIAL-NEEDS'].value,10) > 0)) document.form2['NUMBER-OF-SPECIAL-NEEDS'].value = 0 if(!(parseInt(document.form2['NUMBER-OF-CARERS'].value,10) > 0)) document.form2['NUMBER-OF-CARERS'].value = 0 if(!(parseInt(document.form2['NO-OF-S-CITIZENS'].value,10) > 0)) document.form2['NO-OF-S-CITIZENS'].value = 0 if(!(parseInt(document.form2['NO-OF-ADULTS'].value,10) > 0)) document.form2['NO-OF-ADULTS'].value = 0 var children = parseInt(document.form2['NUMBER-OF-KIDS'].value,10) var low_price = parseInt(document.form2['NUMBER-OF-KIDS'].value,10) + parseInt(document.form2['NUMBER-OF-SPECIAL-NEEDS'].value,10) + parseInt(document.form2['NUMBER-OF-CARERS'].value,10) + parseInt(document.form2['NO-OF-S-CITIZENS'].value,10); // kids field var adults = parseInt(document.form2['NO-OF-ADULTS'].value,10); // adults kd = parseInt (low_price,10) ad = parseInt (adults,10) var freeadults=Math.floor(children/10); // 1 free adult //document.getElementById("freeadults").innerHTML = "Number of Adults that go free: " + freeadults //Adults £8 //Kids, Special Needs, Carers and Senior Citizens 5.25 ad -= freeadults if(ad < 0) ad = 0; var xtotal = (kd*5.25) + (ad* document.form2['TOTAL-COST'].value = xtotal.toFixed(2) } What I need to do is calculate the total values that have been entered, If its less than 15 restrict the form from being submitted or something like that Any help appreciated Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/ Share on other sites More sharing options...
KevinM1 Posted June 3, 2008 Share Posted June 3, 2008 The easiest thing to do would be to assign a variable to each population, so: var myForm = document.forms["form2"]; //we use this later var myFormInputs = document.forms["form2"].elements; //better to put all inputs into a variable that we can access...saves on typing and processing var numKids = parseInt(myFormInputs["NUMBER-OF-KIDS"].value, 10); var numSpecNeeds = parseInt(myFormInputs["NUMBER-OF-SPECIAL-NEEDS"].value, 10); . . . Then add them together and see if they exceed 15. Probably best to do this when the form is submitted: myForm.onsubmit = function() { if((numKids + numSpecNeeds + /* all of the other populations */) < 15) { alert("Must be a minimum of 15 people!"); return false; } else { //submit the form normally } } Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-556643 Share on other sites More sharing options...
stublackett Posted June 4, 2008 Author Share Posted June 4, 2008 Sorry to sound like a complete Newbie, But where does this JavaScript coding go!? Do I include it aswell as the other stuff, or instead? Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-557404 Share on other sites More sharing options...
KevinM1 Posted June 4, 2008 Share Posted June 4, 2008 Sorry to sound like a complete Newbie, But where does this JavaScript coding go!? Do I include it aswell as the other stuff, or instead? You should probably post your entire script, as some of what I wrote may change depending on what else is going on inside of it. That way, I can just post a complete modified version that you can use with minimal fuss. Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-557487 Share on other sites More sharing options...
stublackett Posted June 4, 2008 Author Share Posted June 4, 2008 Ok, Many thanks The script in full is <script type="text/JavaScript"> <!-- function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } 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_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } function calculate() { validkids = false; validadults = false; if(!(parseInt(document.form2['NUMBER-OF-KIDS'].value,10) > 0)) document.form2['NUMBER-OF-KIDS'].value = 0 if(!(parseInt(document.form2['NUMBER-OF-SPECIAL-NEEDS'].value,10) > 0)) document.form2['NUMBER-OF-SPECIAL-NEEDS'].value = 0 if(!(parseInt(document.form2['NUMBER-OF-CARERS'].value,10) > 0)) document.form2['NUMBER-OF-CARERS'].value = 0 if(!(parseInt(document.form2['NO-OF-S-CITIZENS'].value,10) > 0)) document.form2['NO-OF-S-CITIZENS'].value = 0 if(!(parseInt(document.form2['NO-OF-ADULTS'].value,10) > 0)) document.form2['NO-OF-ADULTS'].value = 0 var children = parseInt(document.form2['NUMBER-OF-KIDS'].value,10) var low_price = parseInt(document.form2['NUMBER-OF-KIDS'].value,10) + parseInt(document.form2['NUMBER-OF-SPECIAL-NEEDS'].value,10) + parseInt(document.form2['NUMBER-OF-CARERS'].value,10) + parseInt(document.form2['NO-OF-S-CITIZENS'].value,10); // kids field var adults = parseInt(document.form2['NO-OF-ADULTS'].value,10); // adults field kd = parseInt (low_price,10) ad = parseInt (adults,10) var freeadults=Math.floor(children/10); // 1 free adult //document.getElementById("freeadults").innerHTML = "Number of Adults that go free: " + freeadults //Adults £8 //Kids, Special Needs, Carers and Senior Citizens 5.25 ad -= freeadults if(ad < 0) ad = 0; var xtotal = (kd*5.25) + (ad* document.form2['TOTAL-COST'].value = xtotal.toFixed(2) } //--> </script> Many Thanks Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-557519 Share on other sites More sharing options...
KevinM1 Posted June 4, 2008 Share Posted June 4, 2008 Okay, first, from the looks of things, you probably have a submit element that's something along the lines of: <input type="submit" name="submit" value="submit" onclick="this.calculate();" /> If so, you'll need to remove the onlick or anything referencing JavaScript from it. Now, to the script itself: <script type="text/javascript"> /* Note how there's no HTML comments (i.e., <!-- -->). All modern browsers understand JavaScript, so adding them is pointless. We're going to keep the image caching and swapping functions. I'm not going to re-write them in my coding style, but just be aware that my style is different than the style these initial functions use. I'm just mentioning it because you're a self-proclaimed newbie, so I don't want to throw you off. */ function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } 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_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } var myForm = document.forms["form2"]; //obtain a reference to the form var myFormInputs = myForm.elements; //obtain a reference to all of the inputs in the form itself myForm.onsubmit = calculate; //set the form to run the calculate() function when a user attempts to submit information function calculate() { var validKids = false; var validAdults = false; if(!parseInt(myFormInputs["NUMBER-OF-KIDS"].value, 10) > 0) { var numKids = 0; } else { var numKids = myFormInputs["NUMBER-OF-KIDS"].value; } if(!parseInt(myFormInputs["NUMBER-OF-SPECIAL-NEEDS"].value, 10) > 0) { var numSpecNeeds = 0; } else { var numSpecNeeds = myFormInputs["NUMBER-OF-SPECIAL-NEEDS"].value; } if(!parseInt(myFormInputs["NUMBER-OF-CARERS"].value, 10) > 0) { var numCarers = 0; } else { var numCarers = myFormInputs["NUMBER-OF-CARERS"].value; } if(!parseInt(myFormInputs["NO-OF-S-CITIZENS"].value, 10) > 0) { var numSeniors = 0; } else { var numSeniors = myFormInputs["NO-OF-S-CITIZENS"].value; } if(!parseInt(myFormInputs["NO-OF-ADULTS"].value, 10) > 0) { var numAdults = 0; } else { var numAdults = myFormInputs["NO-OF-ADULTS"].value; } if((numKids + numSpecNeeds + numCarers + numSeniors + numAdults) < 15) //if there are fewer than 15 people { alert("At least 15 people must sign up!"); //alert the user of the error return false; //stop submission } else //else, process like normal { var lowPrice = numKids + numSpecNeeds + numCarers + numSeniors; var freeAdults = Math.floor(numKids/10); numAdults -= freeAdults; if(numAdults < 0) { numAdults = 0; } var total = (lowPrice * 5.25) + (numAdults * ; myFormInputs["TOTAL-COST"].value = total.toFixed(2); return true; //ensure the submission happens } } </script> A few things to note: 1. The biggest thing is that this code may not work as-is. I haven't tested it or anything, it was merely written off the top of my head. That said, I think something along these lines should work for you. The best way to test it is to run the page through Firefox and report back any errors the error console shows you. Bonus points if you have Firebug installed. 2. Do you ever use the validKids and validAdults variables anywhere? I left them in the function, but they don't appear to do anything. 3. Along those same lines, I tried shortening the amount of code where I could. There were several places where you created a new variable for no real reason. Use only what you need. I also took the liberty of reducing the number of document.blah.blah calls. This, too, saves on typing and, more importantly, processing. Instead of forcing the browser to calculate where form2 is, then all its inputs, then the correct input, then that input's value, I stored some of that info in a variable (myFormInputs). No repeat calculations needed. 4. Similarly, using parseInt for data validation isn't the most elegant solution. You can simplify things if you use regular expressions. I left them out because I didn't want to change your code too much, but it's a simple change. In this case, the brute-force method works because you're expecting a base-10 number in each field, so you'd really only be gaining shorter code by using regex, but with more complex values (text), regex is great. I hope this helps a bit. Let me know of any errors. Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-557737 Share on other sites More sharing options...
stublackett Posted June 5, 2008 Author Share Posted June 5, 2008 Nightslyr, Many many thanks! I'm just getting the one error on line 72 and the Error is : "myFormInputs.NUMBER-OF-KIDS" is null or not an object Rest of the script seems to work Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-558139 Share on other sites More sharing options...
KevinM1 Posted June 5, 2008 Share Posted June 5, 2008 Nightslyr, Many many thanks! I'm just getting the one error on line 72 and the Error is : "myFormInputs.NUMBER-OF-KIDS" is null or not an object Rest of the script seems to work Hmm...I'll check it out. Are you using Firefox to test it? Because line 72 is merely a '{' character. Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-558192 Share on other sites More sharing options...
KevinM1 Posted June 5, 2008 Share Posted June 5, 2008 I believe I've found the problem, and, thankfully, it looks like my hunch was correct. The problem is that the script is working before the document is fully loaded. So, the solution is to put the entire script into the window's onload event handler as a function. In other words: <script type="text/javascript"> window.onload = function() { //rest of the script goes here } </script> That should fix things. If it doesn't, let me know. Quote Link to comment https://forums.phpfreaks.com/topic/108541-function-calculate/#findComment-558197 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.