JavaScript - Problems With An Is Not Defined Error And Input Validation
I'm having trouble figuring out this code. I have a isInitialsTextValid function that checks to see if the user enters their initials in the correct format. Then I have a function checkInitials.
In the checkInitials function I am supposed (1)to declare a variable to be used for the boolean value returned by the isInitialsTextValid function.(2)call the isInitialsTextValid function.(3)If the value returned is false, place focus back on initials textbox.(4)If the value return is true call the submit function. I'm not sure what I am doing wrong, but I get a checkInitials is no defined error from firefox and it is pointing to my xhtml file. Here is the relevant code. XHTML FILE Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Form Example</title> <script type = "text/javascript" src= "Lab17.js"> </script> </head> <body onload="giveInitFocus();"> <form name = "form1" action = ""> <p> <input type = "button" value = "Total Cost" onClick = "checkInitials();" /> <input type = "reset" value = "Reset Order Form" name = "reset" /> </p> <hr /> <p> Please Enter the Cashier's Initials. </p> <p> <label> Cashier's Initials: <input type = "text" name = "initials" id = "initials" /></label> </p> <p> JAVASCRIPT FILE Code: function isInitialsTextValid() { var init = document.form1.initials; var position = init.value.search(/^[A-Z]{2,3}$/); if(position !=0) { alert("Initials must be 2 or 3 capital letters" + "\n Please re-enter"); return false; } else return true; } function checkInitials() { var returned; isInitialsTextValid(); if(returned == false) { document.form1.initials.focus(); } else if(returned == true) { handleSubmitClick(); } } Similar TutorialsHi, I have the below function and I keep getting the error Lid is not defined. Code: <script type="text/javascript"> function loadTips(file,ID,File,id){ alert(file); alert(ID); alert(File); alert(id); loadXMLDoc(file,ID); var l=setTimeout("loadXMLDocRefresh(File,id)",10000); } </script> My trigger button is: <input type="button" class="button3" value="Tips" onclick="loadTips('getTees.php','txtHintTees','getLees.php','txtHintLees')" /> So my alert Lid comes up with txtHintLees, so it is working up until the alert. Which leads me to believe that maybe it doesn't like being wrapped in "", without "" though firebug halts the process. I tried wrapping it in {} e.g. {loadXMLDocRefresh(File,id)} but that wasn't liked either. I'll stop my list of things I tried that don't work now. But does anyone have any ideas? The simplified code below works, and should give you an idea of what Im trying to achieve. The final version will have dozens of input fields so you can see why the below method stinks Code: <html><head><title>Values</title> <script type="text/javascript"> <!-- function getid() { var myNum = document.frm1.field1.value; if(myNum == "A"){ document.frm1.field2.value = "1" } else if(myNum == "B"){ document.frm1.field2.value = "2" } else { document.frm1.field2.value = "" } var myNum2 = document.frm1.field3.value; if(myNum2 == "A"){ document.frm1.field4.value = "1" } else if(myNum2 == "B"){ document.frm1.field4.value = "2" } else { document.frm1.field4.value = "" } } //--> </script> </head><body> <form name="frm1" id="frm1"> <input type="text" size="40" name="field1" id="field1" onChange="JavaScript:getid();" /><input type="text" size="4" id="field2" name="field2" /> <br> <input type="text" size="40" name="field3" id="field3" onChange="JavaScript:getid();" /><input type="text" size="4" id="field4" name="field4" /> <br> </form> </body> </html> Each text input will have A or B written in by the user, which should automatically place that letters associated ID in its partner field. If any other letter is entered the ID will automatically be left blank. With the above code I'd need to repeat it over and over for each of the dozens of input fields. The final version wont be using simply A/B either but around 50 possible inputs each with their own ID which would make around 1000 possible variations. What am I missing here that will simplify the process? Thanks Code: $(document).ready(function(){ var theText=["Text one","Text two","Text three", "Text four"]; // Build the array of text var arrayRows = theText.length; //Get the length of the array (Note: This starts at 1 not 0 like the array) var i=0; //Set a counter document.getElementById('textHere').innerHTML =theText[i]; //Fill in the space with the first piece of text time = setTimeout("next()", 2000); function next() { if (i == (arrayRows-1)) { i = 0; }else { i++; } $("#textHere").fadeOut("slow", function(){ document.getElementById('textHere').innerHTML =theText[i]; $("#textHere").fadeIn("slow"); }); } function prev() { if (i <= 0) { // If its below 0 go to the max i = arrayRows-1; }else { i--; } $("#textHere").fadeOut("slow", function(){ //Fade out the area document.getElementById('textHere').innerHTML =theText[i]; //Change the text to the next piece of text $("#textHere").fadeIn("slow"); // Fade in the area }); } $("#prevText").click(function(e) { e.preventDefault(); // Stop the link being a link prev(); }); $("#nextText").click(function(e) { e.preventDefault(); next(); }); }); When i click the links the functions work, however the setTimeout doesnt, can anyone help me figure this out? Greetings all. Please let me apologize in advance if this is a tremendously stupid question, but I'm new to Jquery and ASP... and I'm suddenly building an entire site made of both. *sigh* I keep getting an error message in Firebug in relation to the accordion menu I created. "$ not defined $(function() {" If the navigation is isolated on its own page, the error does not exist. It only occurs once it is brought into the Store Master page. Working Version: http://www.stephenjosephinc.com/testing/ Non-Working Version: http://74.124.26.78/ The following code is cut from the head in the non-functional page: Code: <head id="ctl00_Head1"> <title>Shop Online</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="icon" href="App_Master/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="App_Master/favicon.ico" type="image/x-icon" /> <link type="text/css" href="App_Master/css/custom-theme/jquery-ui-1.8.4.custom.css" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script> <link type="text/css" href="App_Master/theme/ui.all.css" media="screen" rel="stylesheet" /> <script type="text/javascript"> $(function() { $("#accordion").accordion({ collapsible: true, autoHeight: false, header: "h3"} ); }); </script> <link href="App_Themes/DefaultTheme/master.css" type="text/css" rel="stylesheet" /> <link href="App_Themes/DefaultTheme/menu.css" type="text/css" rel="stylesheet" /> </head> If it helps at all, you may view the entire code he http://74.124.26.78/full_code.txt Please note: I DID NOT create the code on the aforementioned page. It's an ugly, nightmarish mess (at least to my non-ASP-loving eyes), so please don't hate me for bad form in the body code. The only code that I wrote for this page is the bit you see above and the hrefs for the side nav. Any help would be massively appreciated! Thank you in advance! Hi, I am trying to get this function to work, it looks great in theory but I keep getting the error message file is not defined. What have I done wrong? The code is: Code: <head> <script type="text/javascript"> function loadXMLDoc(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST",FILE,true); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } xmlhttp.send(); } </script> </head> <body> <input type="button" value="Test" onclick="loadXMLDoc('getToday.php','txtHint');" > <input type="button" value="Test2" onclick="loadXMLDoc('getYesterday.php','txtHintYest');" > </body> Hi, I have the following script which should work in theory, however I get the error message that file is not defined. I have tried playing around with using variables and I can not work out how to correct this. My code is: Code: <head> <script type="text/javascript"> function loadXMLDoc(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } xmlhttp.open("POST",FILE,true); xmlhttp.send(); } </script> </head> <body> <input type="button" value="Test" onclick="loadXMLDoc($File='getToday.php','txtHint');" > <input type="button" value="Test2" onclick="loadXMLDoc($File='getTomorrow.php','txtHintTom');" > Hi all, Trying to use a small bit of script to slide open and closed a div. Copied it from another page where I have it working just fine. Coding in coldfusion. When clicked, nothing happens, and firebug pulls an error of DC_ShowDeptStaff is undefined. Script is: Code: <script type="text/javascript"> function DC_ShowDeptStaff(){ if( document.getElementById("testdiv").style.display=="none" ) { Effect.BlindDown("testdiv"); return false; } else { Effect.SlideUp("testdiv"); return false; } } </script> Call is: Code: <a href="javascript:;" onclick="DC_ShowDeptStaff()" return false;>See All Staff in this Department</a> Full code is: Code: <script type="text/javascript"> function DC_ShowDeptStaff(){ if( document.getElementById("testdiv").style.display=="none" ) { Effect.BlindDown("testdiv"); return false; } else { Effect.SlideUp("testdiv"); return false; } } </script> <cfquery name="getStaffProfileDepartments" datasource="#ATTRIBUTES.datasource#" username="#ATTRIBUTES.username#" password="#ATTRIBUTES.password#"> SELECT spd.staffProfileDepartmentName, spd.staffProfileDepartmentId FROM dccom_twstaffprofilesdepartments spd WHERE spd.instanceId = <cfqueryparam value = "#REQUEST.instanceId#"> AND spd.staffProfileDepartmentIsPublished = 'YES' ORDER BY spd.staffProfileDepartmentDisplayOrder, spd.staffProfileDepartmentName </cfquery> <cfif getStaffProfileDepartments.RecordCount NEQ 0> <cfloop query="getStaffProfileDepartments"> <!---INSIDE LOOP ONE---> <cfoutput> <h3>#staffProfileDepartmentName#</h3> <h4><a href="javascript:;" onclick="DC_ShowDeptStaff()" return false;>See All Staff in this Department</a></h4><br> <div class="testdiv" style="display: none"><h3>Test Success!</h3></div> <cfquery name="getStaffProfiles" datasource="#ATTRIBUTES.datasource#" username="#ATTRIBUTES.username#" password="#ATTRIBUTES.password#"> SELECT sp.staffProfileId, sp.staffProfileName, sp.staffProfilePosition, sp.staffProfilePhone, sp.staffProfileMobile, sp.staffProfileEmail, sp.staffProfileDescription, sp.staffProfileImage, sp.staffProfileDisplayOrder, spd.staffProfileDepartmentName, sp.staffProfileIsDepartmentHead, sp.staffProfileIsPublished FROM dccom_twstaffprofiles sp LEFT OUTER JOIN dccom_twstaffprofilesdepartments spd ON sp.staffProfileDepartmentId = spd.staffProfileDepartmentId AND sp.instanceId = spd.instanceId WHERE sp.instanceId = <cfqueryparam value = "#REQUEST.instanceId#"> AND sp.staffProfileIsPublished = 'YES' AND spd.staffProfileDepartmentId = <cfqueryparam value="#staffProfileDepartmentId#"> ORDER BY sp.staffProfileIsDepartmentHead DESC, sp.staffProfileDisplayOrder, sp.staffProfilePosition </cfquery> <cfif getStaffProfiles.RecordCount NEQ 0> <cfloop query="getStaffProfiles"> <cfoutput> <ul> <cfset cStaffProfileDescription = staffProfileDescription> <cfset cStaffProfileDescription = replace(replace(cStaffProfileDescription,chr(13) & chr(10),"<br>","ALL"),chr(10),"<br>","ALL")> <li> <cfif staffProfileIsDepartmentHead EQ 'YES'> <div class="staffInfo"> <h3>#staffProfileName#</h3> <h3>DEPT HEAD</h3> <cfif LEN(#staffProfilePosition#)><h4>#staffProfilePosition#</h4></cfif> <cfif LEN(#staffProfilePosition#)><p>#cStaffProfileDescription#</p></cfif> <cfif LEN(#staffProfilePhone#)><p>Phone: #staffProfilePhone#</p></cfif> <cfif LEN(#staffProfileMobile#)><p>Mobile: #staffProfileMobile#</p></cfif> <cfif LEN(#staffProfileEmail#)><p><a href="mailto:#staffProfileEmail#">#staffProfileEmail#</a></p></cfif> </div> <cfif LEN(#staffProfileImage#)> <div class="staffImage"> <cfif LEN(staffProfileImage) AND fileExists(APPLICATION.siteFilePath & "contentFiles\components\twStaffProfiles\" & REQUEST.instanceId & "\" & staffProfileImage)><img src="contentFiles/components/twStaffProfiles/#REQUEST.instanceId#/#staffProfileImage#" width="100" height="120" alt="#staffProfilePosition#"> </cfif> </div> </cfif> <cfelse> <h3>HIDDEN STAFF PROFILE</h3> <div class="staffInfo2" style="display:none" > <h3>#staffProfileName#</h3> <cfif LEN(#staffProfilePosition#)><h4>#staffProfilePosition#</h4></cfif> <cfif LEN(#staffProfilePosition#)><p>#cStaffProfileDescription#</p></cfif> <cfif LEN(#staffProfilePhone#)><p>Phone: #staffProfilePhone#</p></cfif> <cfif LEN(#staffProfileMobile#)><p>Mobile: #staffProfileMobile#</p></cfif> <cfif LEN(#staffProfileEmail#)><p><a href="mailto:#staffProfileEmail#">#staffProfileEmail#</a></p></cfif> </div> <cfif LEN(#staffProfileImage#)> <div class="staffImage"> <cfif LEN(staffProfileImage) AND fileExists(APPLICATION.siteFilePath & "contentFiles\components\twStaffProfiles\" & REQUEST.instanceId & "\" & staffProfileImage)><img src="contentFiles/components/twStaffProfiles/#REQUEST.instanceId#/#staffProfileImage#" width="100" height="120" alt="#staffProfilePosition#"> </cfif> </div> </cfif> </cfif> </li> </ul> </cfoutput> </cfloop> <cfelse> <cfoutput> <p>There are Currently No Staff Listed in this Department</p> <br> </cfoutput> </cfif> </cfoutput> <!---end loop one---> </cfloop> </cfif> any input would be appreciated I'm having some issues with firefox, chrome seems to work ok. Firebug is giving me an error stating country is not defined. The line it's saying it's on is where the function for an ajax call to populate a select input on page load. Here's the script that sets up the functions to call and fill the state and city values: Code: <script src="/components/com_helloworld/js/request.js"> /**************************************************** * Ajax call to fill city values ****************************************************/ </script> <script> function handleOnChange(dd1) { var idx = dd1.selectedIndex; var val = dd1[idx].text; var par = document.forms["cbcheckedadminForm", "adminForm"]; var parelmts = par.elements; var cb_statesel = parelmts["cb_state"]; var country = val; var directory = ""+document.location; directory = directory.substr(0, directory.lastIndexOf('/')); Http.get({ url: "./components/com_helloworld/js/regvalues/states/" + country + ".php", callback: fillcb_state, cache: Http.Cache.Get }, [cb_statesel]); } function fillcb_state(xmlreply, cb_stateelmt) { if (xmlreply.status == Http.Status.OK) { var cb_stateresponse = xmlreply.responseText; var cb_statear = cb_stateresponse.split("|"); cb_stateelmt.length = 1; cb_stateelmt.length = cb_statear.length; for (o=1; o < cb_statear.length; o++) { cb_stateelmt[o].text = cb_statear[o]; } } else { alert("Cannot handle the Ajax call."); } } function handleOnChange2(dd1) { var idx = dd1.selectedIndex; var val = dd1[idx].text; var par = document.forms["cbcheckedadminForm", "adminForm"]; var parelmts = par.elements; var cb_citysel = parelmts["cb_city"]; var state = val; var directory = ""+document.location; directory = directory.substr(0, directory.lastIndexOf('/')); Http.get({ url: "./components/com_helloworld/js/regvalues/" + state + ".php", callback: fillcb_city, cache: Http.Cache.Get }, [cb_citysel]); } function fillcb_city(xmlreply, cb_cityelmt) { if (xmlreply.status == Http.Status.OK) { var cb_cityresponse = xmlreply.responseText; var cb_cityar = cb_cityresponse.split("|"); cb_cityelmt.length = 1; cb_cityelmt.length = cb_cityar.length; for (o=1; o < cb_cityar.length; o++) { cb_cityelmt[o].text = cb_cityar[o]; } } else { alert("Cannot handle the Ajax call."); } } </script> And here's how it's being triggered on page load: 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', ''); handleOnChange2(cb_state); }); </script> I'm not sure why it says it's not defined as it clearly is. This error is causing the dependent drop down script to not work in firefox causing the child dropdowns to not hide. I did notice something odd though, if I remove the doctype line it works ok. I did this as firebug was throwing an error on another page claiming it had a syntax error so obviously something somewhere is messed up. 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" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>"> When the doctype lines are removed firebug throws this error: window.document.forms[arguments[i]] is undefined [Break On This Error] for(var j = 0, e = window.document...ts[i]].elements; j < e.length; ++j) { in formmanager.js. I'm getting an '$active is not defined' error, which makes sense because the method that defines it isn't called till 10 seconds after I check if it is defined below. But that's the point. I'm actually checking to see if it is defined, and if it's not, then I defined. However, firebug still gives me the error for this: Code: if ($active == undefined) { $active = $('.paging a.active'); } var triggerID = $active.attr("rel") - 1; var image_reelPosition = triggerID * imageWidth; I also tried: if ($active === undefined) if (!$active) But nothing works. I'm just trying to check if it's not defined, then define it. Yet it won't let me check if it is undefined because it is telling me it's undefined despite the fact I'm checking for that very reason. Thanks for any response. Hi, I have a button that when you click it displays the results of my db in a div. What I am trying to do is to get the results to update every five seconds. I thought setTimeout was the best way to achieve this. However I am getting the error message that ID is not defined on the setTimeout line. I thought it would automatically input ID into the fields marked ID when the onloadXMLDocRefresh('File.php','txtHint') button is clicked? The button works to load the script, but the refreshing the div is not. My script is: Code: <script type="text/javascript"> function loadXMLDocRefresh(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; timer = setTimeout('loadXMLDocRefresh(File,ID)',5000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> Hi, Using a while loop in a function, I am trying to test an input character against a stored string of characters. I want the function to return the input character only if it is not in the stored string of characters. The code I've prepared is as follows: Code: <SCRIPT language = "JavaScript"> var storedLetters = 'sideways'; function requestLetters(aString) { var validLetter =''; var inputLetter = window.prompt('Please input a single lower-case letter', ''); while (storedLetters.indexOf(inputLetter) != -1) { inputLetter = window.prompt('You have already tried ' + inputLetter + ' . Please try another' + ' letter.'); } validLetter = inputLetter; return validLetter; } requestLetters(storedLetters); document.write(validLetter); </SCRIPT> The code works fine if I remove it from the function wrapper but if the function is called I keep getting an error message that the variable validLetter is not defined. Can anyone see why this is the case? Thanks. I have a form where I want certain fields to be visible only if the user clicks a checkbox on the form. Specifically, when Presented_to_Goverment_EntityCheckbox0 is checked, these fields should appear. Code: DropDownList ID="GovEntity" Officials_Last_NameTextBox0 Officials_First_NameTextBox0 Officials_TitleTextBox0 I created two different styles, show below; one makes the fields visible and one hides them Code: <style type="text/css"> .hideit { visibility: hidden; overflow: hidden; position: absolute; } .showit { visibility: visible; overflow: visible; position: static; } </style> Then I surrounded the fields with a div ID'ed as wdiv Code: <div class="hideit" id="wdiv"> Type Government Entity: <asp:TextBox ID="Type_Government_EntityTextBox" runat="server" Text='<%# Bind("Type_Government_Entity") %>' /> <br /> Officials Last Name: <asp:TextBox ID="Officials_Last_NameTextBox" runat="server" style="display:none" Text='<%# Bind("Officials_Last_Name") %>' /> <br /> Officials_First_Name: <asp:TextBox ID="Officials_First_NameTextBox" runat="server" Text='<%# Bind("Officials_First_Name") %>' /> <br /> Officials_Title: <asp:TextBox ID="Officials_TitleTextBox" runat="server" Text='<%# Bind("Officials_Title") %>' /> <br /> </div> I am using the following javascript to change the styles in response to an onclick event. Code: <script language="javascript" type="text/javascript"> function changeDiv(wdiv) { thediv = document.getElementById(wdiv); if(thediv.className == 'hideit'){ thediv.className = 'showit'; } else if (thediv.className == 'showit'){ thediv.className = 'showit'; }} </script> I call the Javascript in this line Code: <asp:CheckBox ID="Presented_to_Goverment_EntityCheckBox" onClick="ChangeDiv(wdiv)" runat="server" /> <br /> However nothing happens when I click the checkbox and if I look in Firefox's error console it says ChangeDiv is not defined. Thanks. im suppose to validate an ID text field so that is it mandatory, and must be 6 numeric digits. The code i have for the ID field is: Code: <form id="ThisForm"> <label for="emId"> Employee ID: </label></td> <input type="text" name="empID" id="emId" ;"/> </form> I'm beginner to javascript and really has no idea what to do, can someone help pls. Anyone know how do I use javascript to limit the numeric amount enetered in a text box less than 1000?
i have been trying to edit the below code so i can validate text fields and numeric fields but whenever i try it bypasses all validation and executed the php script. Can someone please let me know what i'm doing wrong fld = form.elements['name']; if ( !isValidText( fld.value ) ) { msg = 'The name is not valid.'; addValidationField(fld); addValidationMessage(msg); } function isValidText(val) { var re = /^\s{1,}$/g; if ((mytext.value.length==0) || (mytext.value==null) || ((mytext.value.search(re)) > -1)) { return true; }else { return false; } } Code: fld = form.elements['email']; if ( !isValidEmail( fld.value ) ) { msg = 'The email address is not valid.'; addValidationField(fld); addValidationMessage(msg); } the above code calls: Code: function isValidEmail(val) { var re = /^[\w\+\'\.-]+@[\w\'\.-]+\.[a-zA-Z]{2,}$/; // /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,4}(\.[a-z]{2}){0,2})$/i; if (!re.test(val)) { return false; } return true; } the entire script is as follows Code: /* order form code from dyn-web.com */ // onchange of qty field entry function getProductTotal(field) { clearErrorInfo(); var form = field.form; if (field.value == "") field.value = 0; if ( !isPosInt(field.value) ) { var msg = 'Please enter a positive integer for quantity.'; addValidationMessage(msg); addValidationField(field) displayErrorInfo( form ); return; } else { var product = field.name.slice(0, field.name.lastIndexOf("_") ); var price = form.elements[product + "_price"].value; var amt = field.value * price; form.elements[product + "_tot"].value = formatDecimal(amt); doTotals(form); } } function doTotals(form) { var total = 0; for (var i=0; PRODUCT_ABBRS[i]; i++) { var cur_field = form.elements[ PRODUCT_ABBRS[i] + "_qty" ]; if ( !isPosInt(cur_field.value) ) { var msg = 'Please enter a positive integer for quantity.'; addValidationMessage(msg); addValidationField(cur_field) displayErrorInfo( form ); return; } total += parseFloat(cur_field.value) * parseFloat( form.elements[ PRODUCT_ABBRS[i] + "_price" ].value ); } form.elements['total'].value = formatDecimal(total); } function finalCheck(form) { clearErrorInfo(); var msg = '', fld; // final check of quantity entries' validity for (var i=0; PRODUCT_ABBRS[i]; i++) { var cur_field = form.elements[ PRODUCT_ABBRS[i] + "_qty" ]; if ( !isPosInt(cur_field.value) ) { msg = 'Please enter a positive integer for quantity.'; addValidationField(cur_field) } } if (msg) { // one msg for qty flds addValidationMessage(msg); } ///////////////////////////////////////////////////////////////////// // add check on email and any other required fields here fld = form.elements['email']; if ( !isValidEmail( fld.value ) ) { msg = 'The email address is not valid.'; addValidationField(fld); addValidationMessage(msg); } // ///////////////////////////////////////////////////////////////////// if (msg) { // if any error msg's, display and cancel submission displayErrorInfo( form ); return false; } // check if a quantity entered if (form.elements['total'].value == 0) { msg = "You haven't ordered anything."; addValidationMessage(msg); displayErrorInfo( form ); return false; } return true; } function isValidEmail(val) { var re = /^[\w\+\'\.-]+@[\w\'\.-]+\.[a-zA-Z]{2,}$/; // /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,4}(\.[a-z]{2}){0,2})$/i; if (!re.test(val)) { return false; } return true; } // onclick function checkValue(field) { if (field.value == 0) field.value = ""; } // onblur function reCheckValue(field) { if (field.value == "") field.value = 0; } function isPosInt(val) { var re = /^\d+$/ if ( !re.test(val) ) { return false; } return true; } // format val to n number of decimal places // modified version of Danny Goodman's (JS Bible) function formatDecimal(val, n) { n = n || 2; var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) ); while (str.length <= n) str = "0" + str; var pt = str.length - n; return str.slice(0,pt) + "." + str.slice(pt); } I'm trying to figure out how to add a length paramater to this function. Not quite sure how to do it. here's what I tried: Code: var phone = document.getElementById('phone'); if(isNumericdashes(phone, "Please enter a valid phone number")){ return true; } function isNumericdashes(elem, helperMsg){ var numericExpression = /^[0-9\(\)-]+$/; if(elem.value.match(numericExpression) &&(elem.length > 9)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } Hello all, I have in my application input type file for uploading files. How can i do javascript validation to check if filename has special characters in it?? Thanks As you can see the above warning will be only shown when there is an error while inserting the data into the login form. Now I have tried to achieve it by: Hiding the div say "warning". Use a javascript while submitting the form to check for input validation. If found any error, the hidden div "warning" will show above the form as shown as in the image. I have tried it in Edit fiddle - JSFiddle Ples help i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> Hello I have a php page in which I declared a js variable... right at the top of the page... <script type="text/javascript"> var tester = 0; </script> Later in the page I test this variable... <script type="text/javascript"> if (tester==1){ do some stuff!! } </script> But I keep getting an error variable _tester undefined Am I missing something obvious... I am new to js... but this seems really straightforward |