JavaScript - Validator Reports Errors In This Script. Can You Help Please
<script type="text/javascript">
Code: function switch1(div) { if (document.getElementById('one')) { var option=['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']; for(var i=0; i<option.length; i++) { obj=document.getElementById(option[i]); obj.style.display=(option[i]==div)? "block" : "none"; }}}// function switchImg(i){document.images["wine"].src = i;} </script> used in this page seems to object to option.length Frank. Similar TutorialsValidator (My CSE HTML Validator v9.0 ) reports javascript errors but program runs. There seems to be a problem with commands used twice and a missing semi-colon. Also there are problems with Firefox. Unable to reselect another image. OK with IE8. I would appreciate it if someone with better eyesight than me could give the jscript a once over for me. Thanks oin advance. Frank Culprit is here. EDITED. Hi, I've been looking for a client-side form validation script which will check each field before submitting the form. Can anyone point me to a good one that looks professional. I want it to make a nice presentation of any errors as well, perhaps, as showing a 'tick' sign when the field is correctly filled in . bazz On the 'Edit Profile' page of my eCommerce Wordpress Theme (http://www.projectdisobey.com/disobeyclothing), no error message appears when I do any of the following in the ''New Password' and 'Confirm New Password' text fields: 1. 'New Password' and 'Confirm New Password' do not match. 2. 'Confirm New Password' field is left empty. 3. New password is less than 5 characters. 4. New password is exactly the same as the current password. This is the script: Code: <script language="javascript" type="application/javascript"> function chk_form_pw() { if(document.getElementById('new_passwd').value == '') { alert("<?php _e(ENTER_NW_PW_JS_MSG) ?>"); document.getElementById('new_passwd').focus(); return false; } if(document.getElementById('new_passwd').value.length < 4 ) { alert("<?php _e(ENTER_NW_PW_MIN_JS_MSG) ?>"); document.getElementById('new_passwd').focus(); return false; } if(document.getElementById('cnew_passwd').value == '') { alert("<?php _e(ENTER_CONFIRMNW_PW_JS_MSG) ?>"); document.getElementById('cnew_passwd').focus(); return false; } if(document.getElementById('cnew_passwd').value.length < 4 ) { alert("<?php _e(ENTER_CONFIRMNW_PW_MIN_JS_MSG) ?>"); document.getElementById('cnew_passwd').focus(); return false; } if(document.getElementById('new_passwd').value != document.getElementById('cnew_passwd').value) { alert("<?php _e(ENTER_NW_AND_CONFIRM_PW_SAME_JS_MSG) ?>"); document.getElementById('cnew_passwd').focus(); return false; } } </script> I'd be extremely appreciative if anybody could help me fix the script so that it works as it is meant to. Javascript is not something I'm particularly familiar with... Thanks in advance! Hello, I am currently working on my school's website. The site is laid out with a DIV on the left set up as a menu (called "leftmenu") and a DIV to the right to display the content (called "maincontent"). Clicking a link in leftmenu calls a script which changes the content of "maincontent". The script currently works as it should except for one small error. The appropriate heading, text and image load for each link, but the formatting between the image and the paragraph is lost. When the page originally loads, the image is set to "float:left" and the paragraph wraps around it to the right. However, when the script runs and changes the contents, the paragraph no longer wraps around the image, but is written below it. Javascript function: Code: var nov12="News for November 12"; var nov11="News for November 11"; var nov10="News for November 10"; function writeNews(title,image,txt) { document.getElementById("newsTitle").innerHTML=title; document.getElementById("newsImage").src=image; document.getElementById("newsText").innerHTML=txt; } HTML for the links calling the function and maincontent: Code: <div class="leftmenu"> <h3>News</h3> <ul class="leftmenu"> <li class="leftmenu"><a class="leftmenu" href="javascript:writeNews('November 12','img1.jpg',nov12)">Nov 12</a></li> <li class="leftmenu"><a class="leftmenu" href="javascript:writeNews('November 11','img2.jpg',nov11)">Nov 11</a></li> <li class="leftmenu"><a class="leftmenu" href="javascript:writeNews('November 10','img3.jpg',nov10)">Nov 10</a></li> </ul> </div> <div class="maincontent"> <h3 id="newsTitle">School News</h3> <img id="newsImage" class="newsimagestyle" src="img1.jpg" /> <p id="newsText"><img id="newsImage" class="newsimagestyle" src="" />Select the date from the menu on the left for news posted on that day.</p> </div> I have also attached the "before.jpg" and "after.jpg" screen captures from the relevant section of the website so you can see what changes are happening to the formatting. BEFO AFTER: Any help to keep the formatting in the same would be greatly appreciated. Thanks. Phil The following piece of code produces errors and will not validate at W3 validator.. It can be seen in action here. I am not good with JS and any help will be appreciated PS It selects a png according to the time slot. Frank Code: function greet() { var hour = (new Date()).getHours(); var when = (hour > 21) ? "night" :(hour > 17) ? "evening" : ( (hour > 11) ? "afternoon" : "morning" ); document.write('<img src="' + when + '.png" alt="Good ' + when + '"n');} I found this script on a tutorial site but it had no summary of browser compatibility or any other issues. I know absolutely nothing about javascript and, although it works fine when I test it, I would appreciate it very much if someone else would review this page and give me feedback. Code: <head> <script type="text/javascript"> lastone='empty'; function showIt(lyr) { if (lastone!='empty') lastone.style.display='none'; lastone=document.getElementById(lyr); lastone.style.display='block'; } </script> </head> <body> <!--links--> <a href="JavaScript:;" onClick="showIt('divID1')" ">link1</a> <a href="JavaScript:;" onClick="showIt('divID2')" ">link2</a> <a href="JavaScript:;" onClick="showIt('divID3')" ">link3</a> <a href="JavaScript:;" onClick="showIt('divID4')" ">link4</a> <!--layers--> <div id="divID1" style="display:none;">content1</div> <div id="divID2" style="display:none;">.content2</div> <div id="divID3" style="display:none;">..content3</div> <div id="divID4" style="display:none;">...content4</div> </body> Here is a demo of it in action: http://www.mousegrey.com/layers.html Hello! I have started using php/html/javascript just recently so I'm not too familiar with it yet, however I think I've done alright. I have apache installed so I can mess around with my files and perfect stuff, so I've created a form that a user fills out, pushes a button, and it prints the information in an organized fashion. It works perfectly for the most part, and I have a validator script that ensures all of the fields work correctly. All of that works great, however I recently uploaded all of the files to a hosted server and the validator stopped picking up for some reason. Anyone have any idea why on localhost a form validator script would work but hosted it wouldn't? Any insight would be great. I've added the two scripts below: Form (php) code:http://pastebin.com/J83AX6GG Validator (JS) code: http://pastebin.com/LMuLu3Jp Thank you for your time! Hello! I'm doing an assignment that validates a password field, the password field should only contain numbers, however this code only verifies the first number input in the field, which means i need to check through every singel input in the field, so i got a little problem <script> function checkPassword(strng) { var text = strng.value; var regel = text.replace(/[\(\)\.\-\ ]/g, ''); if(isNaN(parseInt(text))) { window.alert("Fel, password is not a number:" + text); } } else { window.alert("correct e-mail and password!"); } } </script> I've been thinking about a for loop should fix the problem, but im new to javascript, some help would be appreciated! Hello, I don't see what the problem is with my form validation script. It does not validate. Please point it out to me. Code: <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["name"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Please enter a valid email address"); return false; } var x=document.forms["myForm"]["message"].value; if (x==null || x=="") { alert("You have not entered a message"); return false; } } </script> html Code: <form name="myForm" action="contact.php" onsubmit="return validateForm()" method="post"> First name: </p> <input type="text" name="name"> </p> Email address: </p> <input type="text" name="email"> </p> Subject: </p> <input type="text" name="subject"> </p> Message: </p> <textarea name="message" rows="15" cols="50"></textarea> </p> <input type="submit" value="Submit"> </form> the script is in the <head> section and html in the <body>. Thank you. I have the following script in the head; Code: <script type="text/javascript"> <![CDATA[ <!--This function validates the data from the three input boxes on the MAILTO form--> function validate() { Check="Valid"; Name=document.contact.name.value; Mail=document.contact.mail.value; Comment=document.contact.comment.value; if (Name=="your name" || Name.length<1) { alert("Please enter your name"); Check="Invalid"; } else if (Mail.indexOf("@")<1 || Mail.indexOf(".")<1) { alert("Please enter a valid email address"); Check="Invalid"; } else if (Comment=="your comment" || Comment.length<1) { alert("Please enter your comment"); Check="Invalid"; } if (Check=="Invalid") { return false; } else { alert("Thank you for your comment"); } } ]]> </script> and the following form in the body; Code: <div> <form name="contact" onsubmit="return validate()" action="email.asp" method="post"> <div class="input_title">Name:</div><input type="text" name="name" size="25" class="input_box" /> <br /> <div class="input_title">Your Email:</div><input type="text" name="sender" size="25" class="input_box" /> <br /> <div class="input_title">Phone Number:</div><input type="text" name="tel" size="25" class="input_box" />(Optional) <br /> Message: <br /> <textarea name="enquiry" cols="50" rows="6" class="input_box"></textarea> <br /> <input type="submit" value="Submit" name="submit" /><input type="reset" value="Reset" name="reset" /> <br /> </form> <br /><br /> </div> It is a aspx file and validates fine as XHTML Trans. Why won't it work? Hello all. I am trying to track down why this custom validator is failing with an error that args is undefined. There are two funnctions - one works and one does not. Here they a the bold italicized item is where the error is being generated. Function validHygieneNote works as expected however. Code: function validClothingNote(val,args) { var radio_choice = false; var chks = document.getElementById('clothingNote'); var chks2 = document.getElementsByName('clothingInadequate'); for (counter=0; counter < chks2.length; counter++) { if (chks2[counter].checked){ var rad_val =chks2[counter].value; }} if((rad_val==1)|| (rad_val==2)) { if ((chks.value=="") || (chks.value.length==0) || (chks.value==null)){ args.IsValid=false; } else { args.IsValid = true; } }} function validHygieneNote(val,args) { var radio_choice = false; var chks = document.getElementById('hygieneNote'); var chks2 = document.getElementsByName('hygieneInadequate'); for (counter=0; counter < chks2.length; counter++) { if (chks2[counter].checked){ var rad_val =chks2[counter].value; }} if((rad_val==1)|| (rad_val==2)) { if ((chks.value=="") || (chks.value.length==0) || (chks.value==null)){ args.IsValid=false; } else { args.IsValid = true; } }} Hello, I am trying to add a simple script to my CSS menu for a little bit more eye candy. However, when I add the script - it causes issues in my online store (ex; the javascript-powered one page checkout stops working). Here is the exact error from the error console: Quote: Error: jQuery.validator is undefined Source File: https://www.gem-tech.com/store/pc/onepagecheckout.asp Line: 288 And here is the exact script: Quote: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript" src="jquery.hoverIntent.minified.js"></script> <script type="text/javascript"> $(document).ready(function() { function megaHoverOver(){ $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Calculate width of all ul's (function($) { jQuery.fn.calcSubWidth = function() { rowWidth = 0; //Calculate row $(this).find("ul").each(function() { rowWidth += $(this).width(); }); }; })(jQuery); if ( $(this).find(".row").length > 0 ) { //If row exists... var biggestRow = 0; //Calculate each row $(this).find(".row").each(function() { $(this).calcSubWidth(); //Find biggest row if(rowWidth > biggestRow) { biggestRow = rowWidth; } }); //Set width $(this).find(".sub").css({'width' :biggestRow}); $(this).find(".row:last").css({'margin':'0'}); } else { //If row does not exist... $(this).calcSubWidth(); //Set Width $(this).find(".sub").css({'width' : rowWidth}); } } function megaHoverOut(){ $(this).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); }); } var config = { sensitivity: 2, // number = sensitivity threshold (must be 1 or higher) interval: 100, // number = milliseconds for onMouseOver polling interval over: megaHoverOver, // function = onMouseOver callback (REQUIRED) timeout: 500, // number = milliseconds delay before onMouseOut out: megaHoverOut // function = onMouseOut callback (REQUIRED) }; $("ul#topnav li .sub").css({'opacity':'0'}); $("ul#topnav li").hoverIntent(config); }); </script> I believe there is some sort of conflict? Not sure though. Any input on this? Thanks, Hi, basically it's a simple postcode validator. It checks to see whether the postcode is in UK format, then tells you if it isn't with an alert box, then I want it to clear the field. The input field's ID is postcode. Code: function testPostCode () { var myPostCode = document.getElementById('postcode').value; if (checkPostCode (myPostCode)) { document.getElementById('postcode').value = checkPostCode (myPostCode) } else {alert ("Please enter your Postcode correctly, this includes:\n \n * Correct Spacing - AA1 1AA \n * Correct amount of letters and numbers. \n \n Sorry if this causes any inconvenience, but it is to your benefit.")}; document.postcode.value=""; } Anyone able to help me? HTML: Code: <script src="./include/js/drinkValidation.js" type="text/javascript"></script> <form name="add-drinks" action="include/add-drink.php" method="POST" onSubmit="return addDrinkFormValidation(this);" enctype="multipart/form-data" > <span id="colour" class='modify_form'> <label for='drinkColour'>Spirit Colour:</label> <br /> <select name='drinkColour' tabindex=1> <option value='' >None</option> <option value='R' >R</option> <option value='G' >G</option> <option value='Y' >Y</option> </select> </span> <div class='modify_form'> <label for='drinkType'>Type:</label> <br /> <select name='drinkType' tabindex=1 onChange="HideObjects(this.value)"> <option value="">Select a Drink type:</option> <option value='Cask' >Cask Ales</option> <option value='Guest' >Guest Ale</option> <option value='Lager' >Lager</option> <option value='Bottled Beers' >Bottled Beer</option> <option value='Wines' >Wine</option> <option value='Ciders' >Cider</option> <option value='Softs' >Soft</option> <option value='Spirits' >Spirit</option> </select> </div> <div id="drinkABV" class='modify_form'> <label for='drinkABV'>ABV:</label> <br /> <input name='drinkABV' size='2' tabindex=4 maxlength="4" placeholder="ie: 4.2"/> <label for='drinkABV'>%</label> </div> <div id="name"class='modify_form'> <label for='name'>Name:</label> <br /> <input name='name' size='25' tabindex=3 placeholder="Drink name"/> </div> <div id="drinkInfo" class='modify_form'> <label for='drinkInfo'>Description:</label> <br /> <textarea name='drinkInfo' rows='5' cols='30' maxlength='255' tabindex=5 placeholder="Max 255 characters"></textarea> </div> <div id="pint" class='modify_form'> <label for='drinkPintPrice'>Pint (£):</label> <br /> <input name='drinkPintPrice' size='10' tabindex=8 /> </div> <div id="halfpint" class='modify_form'> <label for='drinkHalfPrice'>Half Pint (£):</label> <br /> <input name='drinkHalfPrice' size='10' tabindex=7 /> </div> <div id="drinkSpecialPrice" class='modify_form'> <label for='drinkSpecialPrice'>Offer Price (£):</label> <br /> <input name='drinkSpecialPrice' size='10'tabindex=6 /> </div> <div id="drinkbottlePrice" class='modify_form'> <label for='drinkbottlePrice'>Bottle/Spirit Price (£):</label> <br /> <input name='drinkbottlePrice' size='10'tabindex=6 /> </div> <br /> <br /> <input type="file" name="cons_image" /> <br /> <br /> <div id='submit'> <input type='submit' value='Add New Drink' /> </div> <br /> <p><b>Please add the information you wish to add then click Add New Drink</b></p> </form> Javascript containing validation Code: var ck_abv = /[0-9]{1,2}\\.[0-9]{1}$/; var ck_price = /[0-9]{1,2}\\.[0-9]{2}$/; var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_info = /^[A-Za-z0-9 ]{3,255}$/; alert ("Im in the file"); function addDrinkFormValidation(form){ var type = form.drinkType.value; var abv = form.drinkABV.value; var name = form.name.value; var info = form.drinkInfo.value; var pint = form.pint.value; var halfpint = form.halfpint.value; var bottle = form.drinkbottleprice.value; var offer = form.drinkSpecialprice.value; var errors = []; alert (form); alert (type); alert (abv); alert (info); alert (pint); alert (halfpint); alert ("Anything showing"); if(type==0){ errors[errors.length] = "Please select a drink type."; } if(!ck_name.test(name) || (name == "")){ errors[errors.length] = "Please enter a drink name."; } if(!ck_info.test(info) || (info == "")){ errors[errors.length] = "Please enter a drink description."; } if(!ck_abv.test(abv)){ errors[errors.length] = "Illegal character in ABV"; } if(!ck_price.test(pint)){ errors[errors.length] = "Illegal character in pint"; } if(!ck_price.test(halfpint)){ errors[errors.length] = "Illegal character in halfpint"; } if(!ck_price.test(bottle)){ errors[errors.length] = "Illegal character in Bottle/Spirit Price"; } if(!ck_price.test(offer)){ errors[errors.length] = "Illegal character in Offer price"; } if (errors.length > 0) { reportErrors(errors); return false; } return false; } function reportErrors(errors){ var msg = "Please Enter Valid Data...\n"; for (var i = 0; i<errors.length; i++) { var numError = i + 1; msg += "\n" + numError + ". " + errors[i]; } alert(msg); } For some reason i dont know why the javascript isnt reading the function even tho they are correctly named, the file is being read as the 1st test alert comes up. the 2nd one inside the function doesnt know. can anyone point in the right place or show me where i am going wrong. as you can see i have put both my entire form and and the java file up. so you can easily see what goes on #on a note i have multiple forms in a tab system if that has anything to do with it although i shouldnt see why it should. #oh and did i get my regex correct for ck_price e.g "9.99 or 10.99" and ck_abv eg "4.2 or 10.2 or 34" #im also using wampserver 2.1 with win7 and chrome if it's needed thanks ste Because of my rather second-rate vision; I would like to get an editor for my Javascript that will check my syntax for me. Missing or extra brackets, semicolons etc are the bane of my life. Any suggestions welcomed. Frank Hi There, I really need your help. I am aware that there is no isDate() function for javascript, however, how could one check a date against a validator to ensure that the date entered is either returned true or false the date format that I would like to check would consist of the dd/mm/yyyy so essentially: isDate("12/01/2012") would return as true isDate("N/A") = would return as false I have searched high and low and am counting on the experts on this forum for some major help. A huge thanks in advance and I really appreciate everything. Cheers, Jay 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. is there anyway to set my code in javascript to ignore errors I have an error that comes up on ie but everything workes fine and i can't find the source of the error -- can i tell the browser to ignore it? 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. |