JavaScript - Help With A Couple Function Errors, Possbile Alternatives?
Hey guys, as of now these lines of code...
Code: function lettergrade(grade) { if (grade >= 9){ document.write("A") } else if (grade >= 8){ document.write("B") } else if (grade >= 7){ document.write("C") } else{ document.write("F | Warning, your letter grade is very low.") } }; function goletter() { document.write("Sam's letter grade on the test is: " + lettergrade(sam) + ", <br \> Sally's letter grade on the test is: " + lettergrade(sally) + ", <br \> Donald's letter grade on the test is: " + lettergrade(donald)) } ...are supposed to display the "____'s letter grade on the test is: A" or the respective letter, but instead it is displaying this... ABF | Warning, your letter grade is very low.Sam's letter grade on the test is: undefined, Sally's letter grade on the test is: undefined, Donald's letter grade on the test is: undefined Any ideas as to why this is happening? I am a novice javascript user so if there are any good alternatives that are pretty basic i'm open to ideas. Thanks guys. Similar TutorialsHi - I wrote some code that uses the eval function. I am in the process of rewriting the code to improve on it where possible (a learning exercise). I have read that eval is evil because of security concerns and that the eval'd code is not compiled prior to runtime. I don't think my use of eval presents a security concern. However, I wonder if there is some way to replace the eval function with a more natural technique. I have done this using eval(); also using a new Function method. I have tried using a window[] method but I can't get that to work. OK, on the the actual code: The purpose of the javascript is to count keystrokes. I have a bunch of global counter variables declared in this fashion: Code: MyLib.CountQ=0; MyLib.CountW=0; MyLib.CountE=0; MyLib.CountR=0; MyLib.CountT=0; MyLib.CountY=0; MyLib.CountU=0; MyLib.CountI=0; MyLib.CountO=0; MyLib.CountP=0; When the Count function is called I want to update the appropriate counter. Thus: MyLib.Count'+varkeyname+'+=1; Where varkeyname is 'q' or 'w' or 'e' etc. Code: //MyLib is a global variable namespace. function Count() {//updates counters var varkeyname= specialchars(MyLib.KeyName);//identity of the key pressed. var stra="Count"+varkeyname;// string used to change an html value. //var strb=eval("MyLib.Count"+varkeyname+"+=1");//original eval function that worked just fine. var strb='return MyLib.Count'+varkeyname+'+=1';//string to update a counter. var myfunc= new Function(strb);//Function intended to replace the eval function - this also works just fine. document.getElementById(stra).value = myfunc(); ... You can see that I have replaced the eval function with another function - but since this is also not compiled prior to runtime I don't think this is an improvement. I have read about using the window[string] method but I can't get it to work. This is not a critical issue but I'd appreciate any comments. Thanks, Jim Here's the code: Code: for (var i = 1; i < 5; i++) var pl = eval("player" + i) var namepl = eval("document.charInput.name" + i + ".value"); var skillpl = eval("document.charInput.skill" + i + ".value"); var genderpl = eval("document.charInput.gender" + i + ".value"); switch (skillpl) { case "warrior": pl = new player(namepl, skillpl, genderpl, 20, 15, 0, 5, 5, 2, 2, 3, 3, 0, 0); logEntry("black", namepl + " is now a warrior."); break; case "mage": pl = new player(namepl, skillpl, genderpl, 15, 10, 20, 2, 5, 5, 5, 2, 3, 0, 0); logEntry("black", namepl + " is now a mage."); break; case "healer": pl = new player(namepl, skillpl, genderpl, 15, 10, 20, 2, 5, 5, 5, 2, 3, 0, 0); logEntry("black", namepl + " is now a healer."); break; case "archer": pl = new player(namepl, skillpl, genderpl, 20, 15, 0, 3, 3, 2, 2, 5, 5, 0, 0); logEntry("black", namepl + " is now an archer."); break; } } Each player has three form values: document.charInput.name1.value document.charInput.skill1.value document.charInput.gender1.value In the case of the 2nd-4th player, it changes to name2.value, etc. Based on these three inputs, I need to iterate through all four players and make the player object for each of them, as I've done above. If anybody has any ideas on how to correct this or an alternative method, please help. Hello again, I've continued to study and work on JavaScript. I've had some problems with the document.write() function. When I try to do a math problem, the whole content of the page clears out and only displays the solution. For example: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Untitled</title> <script type="text/javascript"> function jahava() { var h = 1 var r = 4 var t = 5 document.write(h += r += t) } </script> </head> <body> <button OnClick="jahava()">Click Me!</button> </body> </html> So If I put other content, like the button I was displaying (which I wanted to stay visible), the function would make them all disappear. I would again appreciate any help towards this matter. Sincerely, Taro B. PS; This is not a calculator related problem, just in-general. Hi Guys, I am a novice at javascript. I possibly need an alternative to document.write to output specifically the value contained in Code: {exp:lg_ml:translate key="phrase[i]"} This syntax is cms specific and carries a value like horse or a translated version of it like Pferd in German. The below code outputs: {exp:lg_ml:translate key="cat"}{exp:lg_ml:translate key="dog"}{exp:lg_ml:translate key="horse"} but I want it to output in the source code of my template so it can execute correctly with predetermined values and not just on screen as the syntax instead of the actual value it holds, if you know what I mean. Anyway after hours of trying and 5 cups of cheap Nescafe coffee I need to achieve exactly the below with an alternative possibly to document.write? I also need to keep the loop. Thanks Code: <html> <body> <script type="text/javascript"> var i; var phrase = new Array(); phrase[0] = "cat"; phrase[1] = "dog"; phrase[2] = "horse"; for (i=0;i<phrase.length;i++) { document.write("{exp:lg_ml:translate key=\""+phrase[i] +"\"}"); } </script> </body> </html> As it is, I'm using Walter Zorn's JS Graphics Library in an attempt to write a small screensaver-type-thing for jailbroken iPhones/iPod touches. However, on my mom's AMD Athlon 64 3000+, the drawing gets pretty laggy, so you can imagine how utterly choppy it is on my iPod. The look I'm going for is the Windows XP Mystify screen saver, with corners bouncing around the screen. So, my first question is this: are there any alternatives for this sort of thing, short of manually generating a video, gif, or multiple images to switch through, or is there any way to make my code more efficient for the CPU? (Code below) NOTE: I know I could make it look a lot nicer by making a 'corner' class, and having each corner be an object (and even nicer by using an array of 'corners'). But I'm not sure that would help the CPU's calculations much, and make the code more efficient as a whole. Code: <div id="Mystify"> <script type="text/javascript"> var mystifyCanvas = new jsGraphics("Mystify"); var tetraCorner1x = Math.floor(Math.random()*300) + 5; var tetraCorner1y = Math.floor(Math.random()*460) + 5; var tetraCorner2x = Math.floor(Math.random()*300) + 5; var tetraCorner2y = Math.floor(Math.random()*460) + 5; var tetraCorner3x = Math.floor(Math.random()*300) + 5; var tetraCorner3y = Math.floor(Math.random()*460) + 5; var tetraCorner4x = Math.floor(Math.random()*300) + 5; var tetraCorner4y = Math.floor(Math.random()*460) + 5; go1x = true; go1y = false; go2x = true; go2y = true; go3x = false; go3y = true; go4x = false; go4y = false; function MystifyJavaScript() { mystifyCanvas.clear(); mystifyCanvas.setColor("#ff0000"); mystifyCanvas.setStroke(2); if (go1x) { tetraCorner1x++; if (tetraCorner1x > 315) { go1x = false } } else { tetraCorner1x--; if (tetraCorner1x < 5) { go1x = true } } if (go1y) { tetraCorner1y++; if (tetraCorner1y > 475) { go1y = false } } else { tetraCorner1y--; if (tetraCorner1y < 5) { go1y = true } } if (go2x) { tetraCorner2x++; if (tetraCorner2x > 315) { go2x = false } } else { tetraCorner2x--; if (tetraCorner2x < 5) { go2x = true } } if (go2y) { tetraCorner2y++; if (tetraCorner2y > 475) { go2y = false } } else { tetraCorner2y--; if (tetraCorner2y < 5) { go2y = true } } if (go3x) { tetraCorner3x++; if (tetraCorner3x > 315) { go3x = false } } else { tetraCorner3x--; if (tetraCorner3x < 5) { go3x = true } } if (go3y) { tetraCorner3y++; if (tetraCorner3y > 475) { go3y = false } } else { tetraCorner3y--; if (tetraCorner3y < 5) { go3y = true } } if (go4x) { tetraCorner4x++; if (tetraCorner4x > 315) { go4x = false } } else { tetraCorner4x--; if (tetraCorner4x < 5) { go4x = true } } if (go4y) { tetraCorner4y++; if (tetraCorner4y > 475) { go4y = false } } else { tetraCorner4y--; if (tetraCorner4y < 5) { go4y = true } } mystifyCanvas.drawLine(tetraCorner1x, tetraCorner1y, tetraCorner2x, tetraCorner2y); mystifyCanvas.drawLine(tetraCorner2x, tetraCorner2y, tetraCorner3x, tetraCorner3y); mystifyCanvas.drawLine(tetraCorner3x, tetraCorner3y, tetraCorner4x, tetraCorner4y); mystifyCanvas.drawLine(tetraCorner4x, tetraCorner4y, tetraCorner1x, tetraCorner1y); mystifyCanvas.paint(); window.setTimeout("MystifyJavaScript()", 10); } MystifyJavaScript(); </script> </div> Please keep in mind, there's a LOT of repeat code, so you only have to read any one part once. To test/see/use the code, you'll need to download wz_graphics.zip. Then download the attached txt file to the same directory as the unzipped wz_graphics, change it to .html instead of .txt, and open it. Hi, I'm newer than a newbie. I wrote a website in html, which has an ecommerce that sends the purchase to paypal. My client wants to offer a coupon. I found code in javascript that validates the coupon, but I want to be able to tell PayPal the discounted amount as this discount will not apply to all customers. PayPal Merchant Services told me that I can not use a variable in the following line: <input name="amount" type="hidden" value="132" /> Is there a way I can use Javascript to do the following? At this time, this code doesn't give me an error, but it doesn't send the amount to PayPal either. <script language="javascript">function validate(text1,text2) { if (text1 == text2) { document.write('<input name="amount" type="hidden" value="0" />') } if (text1 !== text2) { document.write('<input name="amount" type="hidden" value="125" />') }} </script> Thanks for any help. I'm doing an assignment and I'm trying to get these codes to work but nothing works. Can anyone help please? Code: <script type = "text/javaScript"> var animal = prompt("Please enter the name of an animal (elephant would be good!)",""); animal = animal.toUppercase(); if (animal="ELEPHANT") { alert ("Elephants are very large and also gentle."); alert ("Have you ever seen an elephant in the circus?"); } else { alert("You have entered an unknown animal which is called a " + animal); alert("This program will self-destruct in 10 seconds"); alert(" 10 - 9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 ..."); } </script> Code: <script type = "text/javaScript"> var rating = prompt("Enter a movie rating (G, PG, R...)",""); rating = rating.toLowercase() switch (rating) { case "g": alert("G means this movie is rated for General Audiences"); break; case "pg": alert("PG means this movie is rated for General Audiences with Parents attending"); break; case "r": alert("R means this movie is rated for Restricted Audiences. May contain violence."); break; default: alert ("This program is rated G. We are not allowed to comment on the movie rating " + rating); } </script> Hey all, I'm trying to fully understand javascript and have a couple of questions I was hoping you could answer for me. I'm working through a book and in the book I'm creating a Bingo card that generates a random number. I'm pasting the full script below just in case it's needed. Code: function initAll () { for(var i=0; i<24; i++) { setSquare(i); } } function setSquare(thisSquare) { var currSquare= "square" + thisSquare; var colPlace= new Array (0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4); var colBasis=colPlace[thisSquare] *15; var newNum=colBasis +getNewNum()+1; document.getElementById(currSquare).innerHTML=newNum; } function getNewNum() { return Math.floor(Math.random() *15); } //--> </script> 1. What does the [thisSquare] mean in this line of code that is bolded? I mean, I know thisSquare is whatever i is, but am I multiplying it by colPlace or what? 2. Lastly I'm confused by this part of the above code Code: var newNum=colBasis +getNewNum()+1; Why add the +1? I mean, i think getNewNum is set to pull a random number between 1 and 14. If you want to pull a number between 1 and 15, why not multiple Math.random() *16 instead of 15. Am i missing something? Sorry, I'm just not understanding why use the +1 I've put together a spoiler bb code, and I've noticed 2 bugs with it - I'm thinking that it's to do with the javascript end of the code. when the code is used, the page has to be refreshed for the spoiler to open and work correctly, also if there is 2 spoilers on the same page, if i click the second one, it opens the first one and not itself. I didn't type the javascript code I only did the html and css end, so I'm not sure what's going on. If any of you can help me I'd be really grateful. Here is the code: Code: <html> <head> <style type="text/css"> body,input { font-family:"Trebuchet ms",arial;font-size:0.9em; color:#333; } .spoiler { color: #494949; font-size: 10pt; font-weight:bold; text-align:left; background-color: #cbeafe ; border-top: 1px solid #9dc2d9; border-left: 1px solid #9dc2d9; border-right: 1px solid #9dc2d9; border-bottom: 2px solid #9dc2d9; padding: 2px; width:90%; min-height:18px; margin: 1px auto 1px auto; -moz-border-radius: 4px; -webkit-border-radius: 4px; -moz-box-shadow:0 0 2px #cbeafe; -webkit-box-shadow:0 0 2px #cbeafe; } .show { color: #00a2c5; font-size: 10pt; font-weight:bold; text-align:center; background-color: #fff ; border: 1px solid #fff; padding: 2px; width:25%px; min-height:5px; margin: 1px auto 1px auto; -moz-border-radius: 2px; -webkit-border-radius: 2px; -moz-box-shadow:0 0 2px #fff; -webkit-box-shadow:0 0 2px #fff; } .hide { color: #00a2c5; font-size: 10pt; font-weight:bold; text-align:center; background-color: #fff ; border: 1px solid #fff; padding: 2px; min-width:25px; min-height:5px; margin: 1px auto 1px auto; -moz-border-radius: 2px; -webkit-border-radius: 2px; -moz-box-shadow:0 0 2px #fff; -webkit-box-shadow:0 0 2px #fff; } </style> <script type="text/javascript"> function hide(id){ document.getElementById(id).style.display = 'none'; } function show(id){ document.getElementById(id).style.display = ''; } function showSpoiler(obj) { var inner = obj.parentNode.getElementsByTagName("div")[0]; if (inner.style.display == "none") inner.style.display = ""; else inner.style.display = "none"; } </script> </head> <body> <div class="spoiler"><img src="http://i.imgur.com/s5tS1.png" align="left"><img src="http://i.imgur.com/6Uq7Y.png" align="right"> <div id="show"><input type="button" class="show" onclick="hide('show'); show('hide'); showSpoiler(this);" value="Show" /> </div> <div id="hide" class="inner" style="display:none;"> <input type="button" class="hide" onclick="hide('hide'); show('show'); showSpoiler(this);" value="Hide" /> <br /><br />{param}<br /></br> </div> </div> </body> </html> Hi there, I've been a web designer for a while and have always used basic javascript in my pages, but decided recently that I would get right into the nitty gritty, however I'm having a problem with some really basic code. Secondly, the book which I'm using is from 2005 and is extolling the virtues of event listeners and so on, is this still the accepted means of handling events? And thirdly, are there still chasms between the browsers in compatability in this area? I'm aware IE has become more and more compliant recently, is it still necessary to write code to cover different browsers or does it all pretty much work nowadays (besides older browsers)? So, to the code! Basically, the browser doesn't get into the function to display the alert(), and i'm not sure why. (Told you it was basic ) Code: <html> <head> <title>Javascript Testing</title> <script type="text/javascript"> <!-- function aKeyWasPressed(e){ alert('Sausages!'); } var textarea = document.getElementById('myta'); textarea.addEventListener('keyup', aKeyWasPressed, false); --> </script> </head> <body> <textarea id="myta"></textarea> </body> </html> Thanks! I have an ajax member search form that I'm just about done with but I have a couple of really irritating firefox issues. The first one is the lack of support of the click() method. I added the following but it still doesn't want to work: Code: <script> if(typeof HTMLElement != 'undefined' && !HTMLElement.prototype.click) { HTMLElement.prototype.click = function() { var evt = this.ownerDocument.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null); this.dispatchEvent(evt); } } </script> The second issue I'm having is with dependent dropdown selects not hiding in firefox. This seems to be due to the other functions that need to trigger onload and is dependent on what order it's loaded. Here's how I'm handling the onload functions: Code: <script> function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(function() { ajaxFunction(document.getElementById('country').value); handleOnChange(country); setupDependencies('cbcheckedadminForm', 'adminForm', 'locationsearch'); handleOnChange2(cb_state); }); </script> I don't have an issue with either of these in chrome. IE is a WHOLE other story, it's all kinds of wonky there. I still need to go through and do some debugging for that. Any quick ideas off hand on these two issues? I'll try and post the full php file in a reply. hey guys. got acouple questions for my website. im more of a html guy.. and i usually find my scripts online. i reeaaallly appreciate all answers! i have a box: <img id="imgSearch" src="" alt="Websites" /> <input type="button" value="Toggle Search" id="btnSearch" /> ^being the button to toggle between websites. basically i'd like this button to toggle between different websites when clicked. secondly: changing span tag colors html code: Traffic Light: <span id="trafficLight"></span> <input type="button" value="Prevent Accident" id="btnTraffic" /> i'd like to change the color of this span id by pressing the button. so in this case it would change red, yellow green and last: changing the font in a bold tag bold by pressing a button html code: (note, the font weight in normal in css for bold) <b>i want this bold when you hit the button!</b> <input type="button" value="Set Bold" id="btnBold" /> I've tried a couple of different scripts, and I'm getting the same result, so I know I must just be missing something. I'm very new to this, so I'm not figuring it out. I want a text box to show the results of an increment counter. Every time I click a button, the number in the text box increments by one. I know it sounds simple, but it's not working. Help? My code is below: Code: <style type = "text/css"> .tbsize { width: 30px; border: 3px; padding: 10px } </style> <script type="text/javascript"> var i=0; function increase() { ++i; } </script> </head> <body> <div id = "tbsize" class = "tbsize"> <form onsubmit = "return false" action = ""> <table> <td><input type = "text" id = "addone" /></td> <td><input type = "submit" value = "Click to add One" onclick="increase()"></td> </table> </form> </div> </body> </script> I have the following code for determining 30 year amortization for fha and conventional loans: Code: function calc(){ var alrt=""; if (document.getElementById("down").value==""){ alrt+="Down Payment\n"; } if (!document.getElementById("con").checked && !document.getElementById("fha").checked){ alrt+="Loan Type"; } if (alrt!=""){ alert("You Must Fill Out the Following Fields:\n"+alrt); } else { doAmb(); } } function doAmb(){ var pur=purchasePrice; var down=eval(document.getElementById("down").value); if (document.getElementById("type").selectedIndex==1){ downPay=down*.01; downPay=downPay*pur; } else { downPay=down; } var pay=pur-downPay; if (document.getElementById("fha").checked){ pay=pay*(1.0225); } amt=getPayment(pay,360,interestRate); writeData(pur,downPay,amt); } function getPayment(a,n,p) { var acc=0; var base = 1 + p/1200; for (i=1;i<=n;i++) { acc += Math.pow(base,-i); } return a/acc; } function writeData(pp,dp,mp){ document.getElementById("purc").innerHTML=Math.round(pp*100)/100; document.getElementById("mon").innerHTML=Math.round(mp*100)/100; document.getElementById("downP").innerHTML=Math.round(dp*100)/100+" ("+(Math.round(((dp/pp)*100)*100)/100)+"%)"; document.getElementById("loan").innerHTML=Math.round((pp-dp)*100)/100; document.getElementById("inter").innerHTML=interestRate; document.getElementById("ins").innerHTML=insurance; document.getElementById("tax").innerHTML=tax; document.getElementById("tot").innerHTML=Math.round((tax+insurance+mp)*100)/100; document.getElementById("sptype").innerHTML=((document.getElementById("con").checked)?"Conventional": "FHA"); document.getElementById("inputArea").style.display="none"; document.getElementById("outputArea").style.display="block"; } function showIn(){ document.getElementById("cover").style.display="block"; document.getElementById("inputArea").style.display="block"; } It works 100% perfectly in Firefox, but in Internet Explorer, it won't do anything. Also, I know there may be some missing variables, those are in a separate JS file. Edit: Also, just discovered that it works fine when used inline, but loaded from an external file, it returns an "Invalid Character" error. If you go to: http://www.five-nine.net/index2/index.html and click on "Go Ahead what ..... info@five-nine.net" And try to submit the form, it will work in every browser except IE6, IE7, & IE9, (I don't know why IE8 is so different than the rest but w/e)... However I don't see any errors on in the JavaScript. Does anyone know why this would happen in just those three browsers? Hi. I've just finished up a web design I've been working on and of course it looks and works great in FF, but has problems in IE. My question is, how do you see what's wrong in IE? I know how to fix the html/css but how do I see what's going wrong with the javascript and php? Is there link in IE where I can see the errors? Thanks in advance. here is the link where the problem persist http://www.ornusweb.com/what_we_done.html I have mixed 2 scripts the light box script(lightbox.js) and scroller script(scriptaculous.js) the page only works with ie and in other browsers it opens as an image(light box wont work) the errors say 1st error> uncaught script.aculo.us requires the prototype javaScript frame work >1.4.0 scriptaculous.load (anonymous function) 2 error > uncaught typeErrorbject function object(){[native code]} has no method 'extends' (anonymous function) can some one help me solve these problem's i get this error when ever i try to process the form: There was a SyntaxError: Unexpected token < error due to an parsererror condition. Javacsipt/jquery: $(document).ready(function(){ $("#slide").click(function(){ $("#inner-wrapper").slideToggle(); }); $('form #response').hide(); $('#submit').click(function(e){ e.preventDefault(); var valid = ''; var required = ' is required'; var name = $('form #name').val(); var email = $('form #email').val(); var fname = $('form #fname').val(); var femail = $('form #femail').val(); var message = $('form #message').val(); var honeypot = $('form #honeypot').val(); var humancheck = $('form #humancheck').val(); //Error checking if (name == '' || name.length <=2) { valid = '<p>Your name' + required + '</p>'; } if (!email.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/)) { valid += '<p>Your email' + required + '</p>'; } if (fname == '' || fname.length <=2) { valid += '<p>Your friend\'s name' + required + '</p>'; } if (!femail.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/)) { valid += '<p>Your friend\'s email' + required + '</p>'; } if (message == '' || message.length <=5) { valid += '<p>A message' + required + '</p>'; } if (honeypot != 'http://') { valid += '<p><center>Spambots are not allowed.</center></p>'; } if (humancheck != '') { valid += '<p><center>A human user' + required + '</center></p>'; } if (valid != '') { $('form #response').removeClass().addClass('error') .html('<strong>Please correct the errors below.</strong>' + valid).fadeIn('2000'); }else { $('form #response').removeClass().addClass('processing').html('<center>Working...</center>').fadeIn('2000'); var formData = $('form').serialize(); submitForm(formData); } }); }); function submitForm(formData) { $.ajax({ type: 'POST', url: 'emailfriend.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success') .html(data.msg).fadeIn('fast'); if ($('form #response').hasClass('success')) { setTimeout("$('form #response').fadeOut('slow')", 5000); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('form #response').removeClass().addClass('error') .html('<p>There was a <strong>' + errorThrown + '</strong> error due to an <strong>' + textStatus + '</strong> condition.</p>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status) { $('form')[0].reset(); } }); }; php file PHP Code: <?php error_reporting(E_ALL ^ E_NOTICE); sleep(3); $name = stripslashes($_POST[name]); $email = stripslashes($_POST[email]); $fname = stripslashes($_POST[fname]); $femail = stripslashes($_POST[femail]); $message = stripslashes($_POST[message]); $honeypot = $_POST[honeypot]; $humancheck = $_POST[humancheck]; if ($honeypot == 'http://' && empty($humancheck)) { $error_msg = ''; $reg_exp = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/"; if (!preg_match($reg_exp, $email)) { $error_msg .= "<p>A valid email is required</p>"; } if (!preg_match($reg_exp, $femail)) { $error_msg .= "<p>A valid email is required</p>"; } if (empty($name)) { $error_msg .= "<p/>Please provide your name</p>"; } if (empty($fname)) { $error_msg .= "<p/>Please provide your name</p>"; } if (empty($message)) { $error_msg .= "<p>A message is required.</p>"; } if (!empty($error_msg)) { $return['error'] = true; $return['msg'] = "<h3>Oops! Looks like you missed a few fields.</h3>".$error_msg; echo json_encode($return); exit(); }else { $return['error'] = false; $ref=@$HTTP_REFERER; /////Message at the top of the page showing the url//// $header_message = "Hi $fname \n Your friend $name requested you to visit this page at \n $ref \n"; /// Body message prepared with the message entered by the user //// $body_message =$header_message."\n".$message."\n"; // IP address of visitor is added to message, you can remove it if not required.// $body_message .="\n Sent from http://www.separatethescams.com"; //// Mail posting part starts here ///////// $headers=""; //$headers = "Content-Type: text/html; charset=iso-8859-1\n".$headers; // Un comment the above line to send mail in html format $headers4=$email; // Change this to change from address $headers.="Reply-to: $headers4\n"; $headers .= "From: $headers4\n"; $headers .= "Errors-to: $headers4\n"; $subject="$name visit this site!"; mail($femail,$subject,$body_message,$headers); $return['msg'] = " <b><p><center>Thanks for spreading the word! :) " . "<font color='red'>" .$name . "</font>" . " </p>" . "</b>" . "</center>"; echo json_encode($return); } }else { $return['error'] = true; $return['msg'] = "<h3><center>0ops there was a problem submitting the data. Please try again!</center></h3>"; echo json_encode($return); } ?> html file <html> <head> <link rel="stylesheet" href="ajaxform/form.css" type="text/css" media="screen"/> </head> <body> <div id="wrapper"> <h3 id="slide">Email This Page To a Friend</h3> <hr></hr> <div id="inner-wrapper"> <form id="my_form" action="ajaxform/emailfriend.php" method="post"> <div id="response"><!--This will hold error message and response from server. --></div> <div class="inputs"> <p> <label>Name   ; </label> <input name="name" type="text" placeholder="Your Name" class="required" id="name" size="30" /> </p> </div> <div class="inputs"> <p> <label>Email &nbs p; </label> <input name="email" type="text" placeholder="Your Email" class="required" id="email" size="30" /> </p> </div> <div class="inputs"> <p> <label>Friend's Name </label> <input name="fname" type="text" placeholder="Friend's Name" class="required" id="fname" size="30" /> </p> </div> <div class="inputs"> <p> <label>Friend's Email </label> <input name="femail" type="text" placeholder="Friend's Email" class="required" id="femail" size="30" /> </p> </div> <div class="inputs"> <p> <label id="msg">Message </label> <textarea name="message" cols="24" rows="5"type="text" placeholder="Message To Friend" class="required" id="message"></textarea> </p> </div> <div class="button"> <input name="submit" type="submit" id="submit" value="EMAIL PAGE" /> </div> <div class="inputs"> <input type="hidden" name="honeypot" id="honeypot" value="http://" /> <input type="hidden" name="humancheck" id="humancheck" class="clear" value="" /> </div> </form> </div> <!-- inner-wrapper end --> </div> <script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="ajaxform/ajax_submit.js"></script> </body> </html> Hi I am doing validation on a form, but instead of throwing an alert on empty fields I want to highlight those fields indicating error. if all are empty, then i would like to show only 1 generalized error message "Pls. fill the highlighted textboxes.". how do i do this and thanks in advance. The validator showed up these errors on my site. They are from a script, but I know very limited javascript to correct it, to me it seems to be OK. 1. Line 15, Column 23: character "<" is the first character of a delimiter but occurred as data for (var i = 0; i < d.length; ++i) { This message may appear in several cases: * You tried to include the "<" character in your page: you should escape it as "<" * You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&", which is always safe. * Another possibility is that you forgot to close quotes in a previous tag. 2. Error Line 15, Column 23: StartTag: invalid element name for (var i = 0; i < d.length; ++i) { Code: <script type="text/javascript"> window.onload = function() { if (!NiftyCheck()) { return; } Rounded("div#nifty", "#666", "#FFF", 30, 30); } function adjustRadius() { d = getElementsBySelector("div.rounded"); for (var i = 0; i < d.length; ++i) { d[i].parentNode.removeChild(d[i]); } var x = document.getElementById("radiusx").value; var y = document.getElementById("radiusy").value; Rounded("div#nifty", "#666", "#FFF", x, y); return false; } </script> Does anyone know why these errors are coming up on the WC3? |