JavaScript - Variable Returns Correctly In Ff, Incorrect In Chrome
Hi,
I have a global variable that I change depending on what's going on in screen. <script> var closed=true; .... hideInfobox(pinInfobox); alert("closed: " + closed) //returns false in Chrome, true in FF </script> And that function changes that variable. function hideInfobox(pinInfobox) { if(pinInfobox != null) pinInfobox.setOptions({ visible: false }); alert("closed: " + closed) //returns false in Chrome, false in FF closed=true; alert("closed: " + closed) //returns false in Chrome, true in FF current_pid=null; } For some reason, in FF, it modifies the variable as expected. But in Chrome, it doesn't. Why is this? Is there any way to have consistent behaviour in both browsers? Thanks for reading! ~ kberry Edit: In fact: var closed=true; alert("closed: " + closed); returns true in FF, but false in Chrome... why....? *sigh* Similar TutorialsI'm having trouble getting Google Chrome to print the correct content when I change the content of a modal page with JavaScript. This is my code: JavaScript: Code: function printCoupon(couponID) { var originalContents = document.body.innerHTML; var printable = document.getElementById(couponID); var printContents = printable.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; document.getElementById(couponID).scrollIntoView(true); } HTML: Code: <body> <div id="coupon1"><p>Coupon 1 contents</p></div> <div><a href="javascript:void(0)" onclick="printCoupon('coupon1');return false;">Print Coupon</a></div> <div id="coupon2"><p>Coupon 2 contents</p></div> <div><a href="javascript:void(0)" onclick="printCoupon('coupon2');return false;">Print Coupon</a></div> </body> This works in IE8 and FF 3.6, but Chrome 16 prints the original content, not the printable content. UPDATE: I just discovered another problem with this script. In IE9, the parent page is printed along with the modal (the modal looks transparent), instead of just the modal. I am pretty new to Javascript having a bit of a problem with a website with Google Maps integrated. URL is http://beta.5vanmap.com. JS is in /js/map.js. I have two checkboxes (ccCheck and caccCheck). The basis is when the box is ticked, it overlays a KML onto the map. This is working fine in Chrome, but in FF and IE it doesn't work, IE returns 'ccCheck is Undefined'. The code I am using is in the JS file, the bit it gets stuck at is as follows: Code: document.getElementById('ccCheck').onclick = function() { if (ccCheck == 1) { ccCheck = 0; ccOverlay.setMap(null); } else { ccCheck = 1; ccOverlay.setMap(map); } } If I stick a ccCheck = document.getElementById('ccCheck') within the onclick function (before the if statement), it places the overlay onto the map, but then when I untick the box it just stays there. It's such a simple thing (I think), and must be down to IE being pedantic about declaring the variable properly, the question is how should I be doing this? Thanks and regards Noel Every time i click on one of the said elements, it puts "undefined" into the textbox each time i click on an element. it seems to me that the Key_Table[x] is not getting passed correctly. How do i make sure that this is getting passed correctly? Here's my Code: Code: <script type='text/javascript'> // Startup Script if (document.addEventListener) { document.addEventListener("DOMContentLoaded", LoadEventListeners, false); } function LoadEventListeners() { var Key_Table = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]; // Create event Listeners for the alphabetic keys for(var x = 0; x < Key_Table.length; x++) { Key_Table[x] = document.getElementById(Key_Table[x]); Key_Table[x].addEventListener("click", function(){ InsertChar(Key_Table[x]); }, false); } } function InsertChar(Char) { alert("Char is:" + Char); // Textbox data document.getElementById('TextData').value = document.getElementById('TextData').value + Char; } </script> Since the upgrade from chrome 9 to chrome 10 my script is showing an error in my variables when i use boolean expressions. they changed to version V8, Chrome's JavaScript engine. Here is the function function get_form_value(n){ e=document.getElementById(n); if ((e.value)&&(e.value != "")&&(!e.options)) return e.value; if ((e.selectedIndex)&&(e.selectedIndex>0) &&(e.options[e.selectedIndex].value !="")) return e.options[e.selectedIndex].value; // select if ((e.text)&&(e.text.value !="")) continue; if ((e.selectedIndex)&&(e.selectedIndex>0) &&(e.options[e.selectedIndex].text !="")) return e.options[e.selectedIndex].text; // select if ((e.checkbox)&&(e.checkbox.checked)) return true; return false; } When i run it it shows a syntax error: Can someone please help me fix this? I'm developing a chess game recorder (records chess games just like electronic score sheet) and i am trying to write a function that handles the "en passent" rule in chess. However, when i try to test to see if a Black pawn is at a particular x,y location, it is always giving me back "50px". Even when it's not at that location. i uploaded semi-live version to my website he http://daomingjin.googlepages.com/ScoreMate.html you just click on the 'Play' button to start the game here's the function in question: Code: function PossibleEnpassent() { // if a black pawn moved once, and is in the 5th row it is in a situation where maybe can be taken using en passent for (var x = 0; x < 8; x++) { var Offset = x + 1; if (BlackPawnMoved[0] == 1) { alert("alerted"); // the pawn has been moved once var it = document.getElementById("BlackPawn" + Offset + "Image").style.top; alert(it); if(document.getElementById("BlackPawn" + Offset + "Image").style.top == BlockSize * 3) { alert("black pawn in the 5th row"); // and if the white pawn is in the 5th row (y coord) and the x coord of the white piece is 1 block to the right OR left of the black piece if(document.getElementById("WhitePawn" + Offset + "Image").style.top == BlockSize * 3) { if(document.getElementById("WhitePawn" + Offset + "Image").style.left == document.getElementById("BlackPawn" + Offset + "Image").style.left + BlockSize) { // the white pawn and the black pawn are in the 5th row, and they are next to eachother BlackPawnCanEnPassented[x] = 1; alert("ready"); } // Or to the left of it if(document.getElementById("WhitePawn" + Offset + "Image").style.left == document.getElementById("BlackPawn" + Offset + "Image").style.left - BlockSize) { // the white pawn and the black pawn are in the 5th row, and they are next to eachother BlackPawnCanEnPassented[x] = 1; alert("ready"); } } } } } } I am using this script to automatically set the current date on a form... However, when I post the form, it is actually putting the Day +1 into the database (the year and month are correct). So for example if I set the date to June 8, 2011 on the form, it will post into the db as 2011-06-09. I am not sure whats going on... Also, if the form has a missing input field (and the form reloads), the date resets back to the current date, instead of retaining the php-printed date values. In the head, I have: Code: <script> var monthtext=['January','February','March','April','May','June','July','August','September','October','November','December']; function populatedropdown(dayfield, monthfield, yearfield){ var today=new Date() var dayfield=document.getElementById(dayfield) var monthfield=document.getElementById(monthfield) var yearfield=document.getElementById(yearfield) for (var d=1; d<32; d++) dayfield.options[d]=new Option(d, d+1) dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day for (var m=0; m<12; m++) monthfield.options[m]=new Option(monthtext[m], monthtext[m]) monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month var thisyear=today.getFullYear() for (var y=0; y<4; y++){ yearfield.options[y]=new Option(thisyear, thisyear) thisyear-=1 } yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year } </script> In the form I have: Code: <script type="text/javascript"> //populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select) window.onload=function(){ populatedropdown("daydropdown", "monthdropdown", "yeardropdown") } </script> <tr> <td> <select name="Month" id="monthdropdown"> <option value="<?php print "$Month"; ?>"><?php print "$Month"; ?></option> </select> <select name="Day" id="daydropdown"> <option value="<?php print "$Day"; ?>"><?php print "$Day"; ?></option> </select> <select name="Year" id="yeardropdown"> <option value="<?php print "$Year"; ?>"><?php print "$Year"; ?></option> </select> </td> </tr> Code: <script> // Declared Constants MORSE_ALPHABET = new Array ( '.-', // A '-...', // B '-.-.', // C '-..', // D '.', // E '..-.', // F '--.', // G '....', // H '..', // I '.---', // J '-.-', // K '.-..', // L '--', // M '-.', // N '---', // O '.--.', // P '--.-', // Q '.-.', // R '...', // S '-', // T '..-', // U '...-', // V '.--', // W '-..-', // X '-.--', // Y '--..' // Z ); CHAR_CODE_A = 65; var CTS = prompt('Enter Morse code','here') var inMessage = CTS.split(' '); searchLocation(inMessage,MORSE_ALPHABET) function searchLocation(targetValue, arrayToSearchIn) { var searchIndex = 0; // Iterative counter for(i=0;i < targetValue.length;) { targetValue = targetValue[i]; // Search until found or end of array while( searchIndex<arrayToSearchIn.length && i != targetValue.length && arrayToSearchIn[searchIndex]!=targetValue ) { i++ searchIndex++; } if(searchIndex<arrayToSearchIn.length) { return String.fromCharCode(CHAR_CODE_A + searchIndex); } else { return -1; } } } document.writeln(searchLocation(inMessage,MORSE_ALPHABET)); </script> <head> </head> <body> </body> This is my code and i have figured it to create an array from the prompt and then use the function to return the first array it finds but i cant seem to make it go on to the next index of the array. I know that when you return a value the function closes and i have tried to store my return in a variable but its not working the way i want it to or I'm not writing the correct command or is there away to do multiply returns, i think what i need to do is simply but i have been staring at this screen for a while now and just cant see it. Please help me. Thanks Hi all. New here as you can probably tell, and I have a problem... I want to know how to find out the viewport height in IE. I have been trying to use document.body.clientHeight, which is supposedly exactly what I am after, but the results were always way too small to be the correct one. As a test, I whacked a div in my page and made it 4000px tall, and ran document.body.clientHeight from IE's debugger and it returned a number over 4000px. It seems as thought clientHeight is actually returning the total height of the document, not the viewport size. Thanks for any help. hi here is a code i use to calculate distance b//w 2 places using google api... it works perfectly and shows the results in the html but when i add a return statement at the end of the function showlocation() it returns undefined.. why it is so.. how to resolve it??? 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> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="robots" content="noindex,follow" /> <title>Calculate driving distance with Google Maps API</title> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAMK3PClIOG6IUkYprx4EfNxSY_HQRLXr6AGORx7Qh39w3-je8JxRROt5eJTcDPJ9nGnVn9xXKTQ2l8Q" type="text/javascript"></script> <!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html --> <script type="text/javascript"> var geocoder, location1,addr1,addr2, location2, result1,gDir; function coolAl(add1,add2) { addr1=add1; addr2=add2; var result= return initialize(); showLocation(); alert(result); } function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; result1=location1.address + ' (' + location1.lat + ':' + location1.lon + ')/' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')/' + drivingDistanceKilometers + ' kilometers'; document.body.innerHTML=result1; return drivingDistanceKilometers; }); } function showLocation() { geocoder.getLocations(addr1, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(addr2, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); } </script> </head> <body onload="coolAl('pune','mumbai')"> </html> Suppose we have following javascript codes: Case 1. var foo = function () { var x = "hello"; var bar = function () { alert(x); } return bar; } var bar_ref= foo(); document.write(bar_ref()); // it pops up "hello" and print-outs "undefined". If we modified above code slightly, shown as follow: Case 2. var foo = function () { var x = "hello"; var bar = function () { alert(x); } return bar(); } var bar_ref= foo(); document.write(bar_ref()); // it only pops up "hello". As you can see, Case 2 modified the return value from "return bar" to "return bar()," which won't cause the "undefined" output. To me, it looks like when the JS interpreter executes the line "bar_ref();" it triggers the execution of function "foo", besides both "return bar" and "return bar()" do the same job which is to execute function body of "bar". The only difference is that after the execution of function bar, its function body does not exist anymore, so when the interpreter executes the line "return bar;" it follows the function identifier "bar" and ends up with "undefined". This is why the Case 1 gives us "undefined", but I am not quite clear about why the Case 2 can trace down to the function body of "bar". Do you have any ideas about such difference outputs? Dan Hi all, I have a simple XML file that looks something close to this: Code: <presence id="12345"> <status>in a meeting</status> <priority>1</priority> </presence> <x> <picture>blahblah</picture> </x> <x> <hash>string</hash> </x> I need javascript to pull the status from this file. Here's what I have for that: Code: <span id="login_status"></span> <span id="secondlogin_status"></span> <script type="text/javascript"> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","https://www/user1.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.getElementById("login_status").innerHTML= xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue; document.getElementById("priority").innerHTML= xmlDoc.getElementsByTagName("priority")[0].childNodes[0].nodeValue; xmlhttp.open("GET","https://www/user2.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.getElementById("secondlogin_status").innerHTML= xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue; document.getElementById("second_priority").innerHTML= xmlDoc.getElementsByTagName("priority")[0].childNodes[0].nodeValue; </script> Here's my problem: If my xml file only has the one "parent" (meaning: Code: <presence id="12345"> <status>in a meeting</status> <priority>1</priority> </presence> ) this works WONDERFULLY. However, when the second and third "parents" are added (<x>), the script returns blank output in the spans. I feel almost certain my issue is related to this: http://codingforums.com/showthread.php?t=140810 but I've tried to switch that around but it doesn't seem to provide any different results. If you require a bit more info on the project itself, here's a rundown: This xml file is created by an internal chat app at my office. Each employee has their own xml file listing their current availability and status (hence "in a meeting"). This will be used to determine the availability of certain individuals in the building without having to be logged in to the chat app. That's why there's multiple xml files going to be used (roughly 10-15 in the end). RESOLVED Thank you! Greetings all! Im looking for some help regarding responseText, so please have a look im so mad right now because i have been struggeling for hours XMLHttpRequestObject.responseText returns correct value when i do alert(XMLHttpRequestObject.responseText); see line PHP Code: var fnWhenDone = function (XMLHttpRequestObject) { alert(XMLHttpRequestObject.responseText); }; But problem is that i want to save down the response to a variable... so i try to change it into PHP Code: var fnWhenDone = function (XMLHttpRequestObject) { varTest = XMLHttpRequestObject.responseText; }; When i try to alert varTest later i get "Undifined"... im pretty new to javascript and have been stuck for hours ... See full code below PHP Code: var myConn = new XHConn(); if (!myConn) { alert("XMLHTTP not available. Try a newer/better browser."); } var fnWhenDone = function (XMLHttpRequestObject) { alert(XMLHttpRequestObject.responseText); }; myConn.connect("validateSearch.php", "POST", "foo=bar&baz=qux", fnWhenDone); function XHConn() { var xmlhttp, bComplete = false; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }}} if (!xmlhttp) return null; this.connect = function(sURL, sMethod, sVars, fnDone) { if (!xmlhttp) return false; bComplete = false; sMethod = sMethod.toUpperCase(); try { if (sMethod == "GET") { xmlhttp.open(sMethod, sURL+"?"+sVars, true); sVars = ""; } else { xmlhttp.open(sMethod, sURL, true); xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1"); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && !bComplete) { bComplete = true; fnDone(xmlhttp); }}; xmlhttp.send(sVars); } catch(z) { return false; } return true; }; return this; } I know there is probably going to be an embarrassingly simple answer to my issue (like I am pointing to the wrong place in the DOM) but here goes. Why is the value of overflow not being returned by the below script? Code: <style type="text/css"> div.fbOverflow_Scroll { position:absolute; top:20px; left:20px; z-index:27; overflow:scroll; overflow-x:hidden; height:30px; width:100px; background-color:#FFB60D; border:1px Solid #000000; } </style></head><body><form method='post' enctype='multipart/form-data' id='myForm' name='myForm'> <!-- **** lab(Box10pt, fbOverflow_Scroll, , Extra=) --> <div class='fbOverflow_Scroll' id='fbOverflow_Scroll' position=relative > This is stuff inside of a little scrolling area of the form</div> <script language="JavaScript"> alert(document.getElementById('fbOverflow_Scroll').style.overflow); </script> </form> Hi, I found this regular expression on the internet and it works fine when I test it in various validators on the web. Code: ^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$ It's purpose is to validate dates entered as mm/dd/yyyy, m/dd/yyyy, mm/d/yyyy or m/d/yyyy. When I try it with the code below it always returns null. Code: function isValidDate(/* String */ p1_date) { var x = "^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$"; var re = new RegExp(x); var myValid = p1_date.match(re); alert("p1_date: " + p1_date + "\nmyValid: " + myValid); return myValid; } Suggestions? Hello, When I run the following code, the .Length function returns "undefined." Please help! This is driving me crazy. Code: var strTest = 'test'; alert(strTest.Length); Using the typeof function, I know that JS is treating the variable as a string. Any suggestions? Hi, I have the below code it works, but there a problem. If you press return to drop a line it counts that as a letter/number. Is there a way to fix it? <html> <head> <title></title> </head> <body> <script language="JavaScript"> function CheckCount() { var maxChar = 2000000; if(document.frmMain.txtDetail.value.length > maxChar) { return false; } else { document.frmMain.txtCount.value = document.frmMain.txtDetail.value.length; } } </script> <body> <form name="frmMain" method="post"> <textarea name="txtDetail" cols="40" rows="5" id="txtDetail" onKeyUp="return CheckCount()"></textarea> <br> <input name="txtCount" type="text" id="txtCount" style="width:65px;" value="0"> </form> </body> </html> AJAX XMLHttpRequest responseText returns undefined but alert returns expected text. Code: function getFile(fileToOpen) { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { //alert(xmlhttp.responseText); return xmlhttp.responseText; } } xmlhttp.open("GET",fileToOpen,true); xmlhttp.send(null); } Code: document.getElementById('widgetOptionsShadow').innerHTML = '<div id="widgetOptions">' + getFile('/togglePauseInit.php?g=<?php echo $gadgetName; ?>') + '</div>'; Hello all is it possible to strip leading (meaning at the VERY begining of the text) and trailing (anything at the end of the text) carriage returns with reg ex? so if smbody enters return return return start txt entry ----> keep all other returns in paragraph sloppy ending retrun return return it would remove the start and end returns I'd like to add it to this if possible. Code: comts = comts.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces low tech (validation script done trying to improve on it now) I am confused about what the return keyword is actually returning when returning an object, a primitive, or a function. My confusion is compounded by the fact that I'm not sure if a function is an object or not. According to the book JavaScript Programmer Reference it is: "All functions in JavaScript are first class objects , meaning they can be passed around like any other object reference. In fact, regardless of how they are created, functions are instances of a global object named (aptly) Function." However, someone else states that a function is not an object. An object is a set of primitives and references. A function is executable code. Functions become objects through the use of the new operator. Yet, in the book I mentioned, it says you don't need the new keyword to execute the function as an object, as it already inherits from the object Function when the function keyword is used: Code: function functionName([argname1 [, ...[, argnameN]]]) { statements; } So there's one source of contradiction. Now the bigger issue is what is going on when the return keyword is used. Notice the Validation() function returns an object as its last expression. This technique is common, where you return an object which contains functions in form of object notation. I believe this is done so that we create a closure so that when the intepreter exits the Validation() method, since we created a closure by returning an object, which contains the inner functions addRule and getRule, the local variables of Validation() are not destroyed, given that we can reference them through the two inner functions that make use of the local variables of the outer function. So when we use the return keyword on an object literal, and then exit the function, when we call one of the inner functions as we do later: Code: var rule = $.Validation.getRule(types[type]); essentially getRule() is called, passes an argument, which is received by the inner function as parameter we call name: Code: getRule : function(name) { return rules[name]; } First, note that the return {} is written in object notation, therefore making getRule a local variable and, thus, private function only accessible through the namespace of Validation(). Validation() declares the rules local variable and because of the closure, we can access the rules local variable through the getRule() inner function. *****Here's the part that really thows me off. We return rules[name]. So let's say name is equal to email. This is an associative array so email (held in name) is a property of rules. So here we return the object's property: Code: return rules[name]; And then assign it to a local variable called rule: Code: var rule = $.Validation.getRule(types[type]); So when we return an object rules[name], do we return a reference to an object or a value? In other words, by returning rules[name], where name is equal to email, are we then returning a reference to the following object literal: Code: email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." } And if we are returning a reference, by returning a reference, are we essentially pointing to this object when we assign it to rule? In other words, the variable rule is just pointing to the object literal? And is that the reason we can then access the check function or msg local variable through rule using dot notation, because rule points to the email object literal? Now the ultimate brain twist for me is that if a function is an object, then why when return a function, it returns a value, such as a boolean, if an object only returns a reference and not the value? Code: //Validation is a local variable as it is in a self-executing anonymous function. The purpose of the said anonymous function is to pass the jQuery object as a parameter $ so the $() function will be in scope of the anonymous function and not interfere with other libraries that make use of the same function technique - in the global scope. (function($) { var rules = { email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." }, url : { check : function(value) { if(value) return testPattern(value,"https?://(.+\.)+.{2,4}(/.*)?"); return true; }, msg : "Enter a valid URL." }, required : { check: function(value) { if(value) return true; else return false; }, msg : "This field is required." } } var testPattern = function(value, pattern) { var regExp = new RegExp("^"+pattern+"$",""); return regExp.test(value); //The test() method is built into javascript } return { addRule : function(name, rule) { rules[name] = rule; }, getRule : function(name) { return rules[name]; } } } /* Form factory */ var Form = function(form) { var fields = []; $(form[0].elements).each(function() { var field = $(this); if(field.attr('validation') !== undefined) { fields.push(new Field(field)); } }); this.fields = fields; } Form.prototype = { validate : function() { for(field in this.fields) { this.fields[field].validate(); } }, isValid : function() { for(field in this.fields) { if(!this.fields[field].valid) { this.fields[field].field.focus(); return false; } } return true; } } /* Field factory */ var Field = function(field) { this.field = field; this.valid = false; this.attach("change"); } Field.prototype = { attach : function(event) { var obj = this; if(event == "change") { obj.field.bind("change",function() { return obj.validate(); }); } if(event == "keyup") { obj.field.bind("keyup",function(e) { return obj.validate(); }); } }, validate : function() { var obj = this, field = obj.field, errorClass = "errorlist", errorlist = $(document.createElement("ul")).addClass(errorClass), types = field.attr("validation").split(" "), container = field.parent(), errors = []; field.next(".errorlist").remove(); for (var type in types) { var rule = $.Validation.getRule(types[type]); if(!rule.check(field.val())) { container.addClass("error"); errors.push(rule.msg); } } if(errors.length) { obj.field.unbind("keyup") obj.attach("keyup"); field.after(errorlist.empty()); for(error in errors) { errorlist.append("<li>"+ errors[error] +"</li>"); } obj.valid = false; } else { errorlist.remove(); container.removeClass("error"); obj.valid = true; } } } /* Validation extends jQuery prototype */ $.extend($.fn, { validation : function() { var validator = new Form($(this)); $.data($(this)[0], 'validator', validator); $(this).bind("submit", function(e) { validator.validate(); if(!validator.isValid()) { e.preventDefault(); } }); }, validate : function() { var validator = $.data($(this)[0], 'validator'); validator.validate(); return validator.isValid(); } }); $.Validation = new Validation(); })(jQuery); Thanks for any response. |