Crawlicious | tools for web business

TAG | javascript

Mar/10

9

awesome jquery manual

Here is a link to an awesome jquery manual that is so easy to use.  Thanks Remy and Yehuda!

Visual JQuery

, Hide

Mar/10

2

javascript regex confusion

I had some confusion today with javascript and regular expressions. It was really a dumb mistake because it turned out to be an incorrectly escaped dot (.). Basically I was trying to detect something that had a literal dot in it.  I had escaped the literal dot, but it was being seen by the regex engine as a dot wildcard.  Part of the confusion was that in the string form of a regular expression you need to escape with 2 backslashes and in the perl/slash form you escape with 1 backslash.

To demonstrate I will put up some alerts that you can run in your error console in FF, or throw on a page.  My goal below is to show true when we find the string “test.it”.  You will see that the (.) needs double escaping in string object syntax and needs single escaping in perl syntax.


// using perl type syntax
alert("is match? " + /test\\.it/.test('testXitok')); // => is match? false  (extra escape problem masked, it will hurt us later)
alert("is match? " + /test\\.it/.test('test.itok')); // => is match? false (should have been true!!!! extra escape got us!)
alert("is match? " + /test\.it/.test('testXitok')); // => is match? false (correct with single escape)
alert("is match? " + /test\.it/.test('test.itok')); // => is match? true (correct with single escape)

// using string object method syntax
alert("is match? " + (null != "testXitok".match("test\\.it"))); // => is match? false (correct with double escape)
alert("is match? " + (null != "test.itok".match("test\\.it"))); // => is match? true (correct with double escape)
alert("is match? " + (null != "testXitok".match("test\.it"))); // => is match? true (single escape got us here!  It hurts!)
alert("is match? " + (null != "test.itok".match("test\.it"))); // => is match? true (single escape problem is masked)

Moral of the story, go read the stinking book.  It is such a temptation to be a javascript hacker instead of doing it right.  Well, no more time to hack at javascript, I gotta move on to the next project!

Eric

, , Hide

I had a problem with getting a web application working on IE8 correctly.  I have a workflow type application, and when I would pass two particular pages in the workflow, I would lose the ability to go back and forth in browser history.  The buttons would just gray out.  I tried a bunch of different things and searched the internet all to no avail.  I did notice however that the 2 pages where it would get corrupted were very large, as I had many forms on them with a massive hidden variable that I just plugged into each form.  So, I used jquery to copy the massive parameter to where I need it on submit, instead of in every form and now the page is MUCH smaller.  This has solved my problem!

So, if you are losing your mind because IE is losing your browser navigation buttons, try reducing the size of your page and see if that won’t help you too.

Eric

, , Hide

I have been tracking down a nasty bug in my code over the last 6 hours.  Here is the scenario.  I have a section of nodes on my webpage that has fields and those fields handle events from the user.  For example, I have a name field that when typed into there is an autocomplete box that pops up.  The user has the ability to duplicate the entire section of nodes so that they can create more items.  I am using my own node copy code which consists of taking the innerHTML from the first node and parsing out some things, incrementing ids and then plugging it back into the system by appending it after the original node.  I am using jQuery for the event handling, but not for the node copy, since the node copy has some custom stuff that I have to do.

The bug occurs only on IE when I copy the nodes and then try to fire an event by typing in the field.  What happens is that the event handler for the SUBSEQUENT input boxes can not be fired until I modify the field in the ORIGINAL node block.  Then I get BOTH events!!!  Nasty huh?

The solution actually lies in jQuery’s clone function.  Here you see that when they do a clone they will eliminate the property that is embedded in the html called jQuery12341234=”2″ (those number are some internal jQuery identifier, probably for the event handler).

To fix the bug all I had to do was remove that attribute and definition and viola it works!

Here is jQuery’s replace from their clone function.


html.replace(/ jQuery\d+="(?:\d+|null)"/g, "")

My approach (before I found that jQuery was doing it also was this.


html.replace(/jQuery\d+=["']\d+["']/g, "")

Since jQuery programmers know more than me (i.e. when null might be in that field) I just ditched mine and used theirs.

Have a great day!

Eric

, Hide

I am using jquery with the Devbridge autocomplete plugin.  It is an awesome tool.  Unfortunately we had a bug reported that on IE6 the autocomplete box does not correctly cover up the other controls on the page.  There are select boxes below the field with the drop down and when everything else is covered up, these select boxes stick out like a sore thumb.

Normally you would use the bgiframe plugin for jquery to address this problem, but in this case we don’t have a reference to the dropdown list once it is filled in from the ajax call.  So, my solution was to add a simple callback to the autocomplete plugin that is fired off after the list is populated and made visible.  That gives me the option that simply takes the list container and calls bgiframe on it.  And viola!  My dropdown list covers up all the controls underneath, even the select lists.

Here is a patch if you would like to patch the autocomplete plugin.  Note, it also contains a fix from my last post about using multiple fields as input (the Devbridge autocomplete part is at the bottom of the post).

--- jquery.autocomplete.js  2009-09-27 23:15:14.000000000 -0600
+++ ../jquery.autocomplete.js   2010-01-29 15:29:14.000000000 -0700
@@ -230,6 +230,9 @@
     },^M
     ^M
     getSuggestions: function(q) {^M
+      if (this.options.noCaching) {^M
+        this.clearCache();^M
+      }^M
       var cr, me;^M
       cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];^M
       if (cr && $.isArray(cr.suggestions)) {^M
@@ -280,6 +283,7 @@
       }^M
       this.enabled = true;^M
       this.container.show();^M
+      if ($.isFunction(me.options.onListShow)) { me.options.onListShow(this.container); }^M
     },^M
 ^M
     processResponse: function(text) {^M

Download the actual patch right here!  jquery.autocomplete.js.patch

Remember, to patch your file, simply cd to where your jquery.autocomplete.js file resides (and copy in this patch to that directory to a file called jquery.autocomplete.js.patch) and run this command


patch jquery.autocomplete.js < jquery.autocomplete.js.patch

Now, once you have that file patched, you can do this sort of thing with your autocomplete options.


$("input[name*=some_name], input[name*=some_other_name]").each(function(i) {
$(this).autocomplete(
{
serviceUrl:baseURL + '/lib/dostuffremotely',
minChars:3,
width:500,
maxHeight:400,
zIndex: 9876,
deferRequestBy: 0, //milliseconds
params: {
'prefix':'xyz',
'column':'abc'
},
onListShow: function(container) { container.bgiframe(); }, // LOOK HERE, THIS IS NEW!!!
onSelect: function(value, data){  // "this" is NOT defined here
// handle onselect
}
}
);

Happy jquerying!

Eric

http://www.devbridge.com/projects/autocomplete/jquery/local/downloads/jquery.autocomplete-
http://www.devbridge.com/projects/autocomplete/jquery/local/downloads/jquery.autocomplete-1.1.zip

, Hide

This is in response to a question asked about a jquery autocomplete plugin.

stackoverflow question

The question was, if you are using this jquery autocomplete plugin how do you get the .autocomplete function to include other fields so that you can have a context type of search.  One person (bendewey) answered that you can do the following.

var selectedCategory = $('.categories').val();
var query = '';
if (selectedCategory !== 0)
{
query = '?category=' + selectedCategory;
}
$("#suggest4").autocomplete('search_service.svc' + query, {
// options
});

This is 1/2 correct.  The problem is that when .autocomplete() is called, the url + query are evaluated immediately which means that the current (at time of page loading most likely) selected category value will ALWAYS be used when autocomplete is called.  That means that if the user selected a different category, the new value will not be passed with the query.  Here is a patch to the autocomplete code that will fix it.  After running the patch, you will be able to pass a function to your .autocomplete call (instead of a string url) and then each time autocomplete runs, the function will be run to create the right params.

to run patch:
1. cd to the directory where your jquery.autocomplete.js file exists

2. copy the patch file to a file called jquery.autocomplete.js.patch (in the above mentioned directory)
3. run patch < jquery.autocomplete.js.patch

to use the patch:
do what bendewey said above, except for you need to make the 1st arg of .autocomplete to be a function that returns the proper query, like this…

$("#suggest4").autocomplete(function() {
 var selectedCategory = $('.categories').val();
 var query = '';
 if (selectedCategory !== 0)
 {
   query = '?category=' + selectedCategory;
 }
 return 'search_service.svc' + query; }, {
 // options
 }
);

Here is the patch (you can download the file below):


--- jquery.autocomplete.js.orig 2010-01-15 11:00:55.000000000 -0700
+++ jquery.autocomplete.js  2010-01-15 11:04:02.000000000 -0700
@@ -14,7 +14,7 @@

 $.fn.extend({
 autocomplete: function(urlOrData, options) {
-       var isUrl = typeof urlOrData == "string";
+       var isUrl = typeof urlOrData == "string" || typeof urlOrData == "function";
 options = $.extend({}, $.Autocompleter.defaults, {
 url: isUrl ? urlOrData : null,
 data: isUrl ? null : urlOrData,
@@ -346,10 +346,14 @@
 term = term.toLowerCase();
 var data = cache.load(term);
 // recieve the cached data
+        var url = options.url;
+        if (typeof url == "function") {
+            url = options.url();
+        }
 if (data && data.length) {
 success(term, data);
 // if an AJAX url has been supplied, try loading the data now
-       } else if( (typeof options.url == "string") && (options.url.length > 0) ){
+       } else if( (typeof url == "string") && (url.length > 0) ){

 var extraParams = {
 timestamp: +new Date()
@@ -364,14 +368,16 @@
 // limit abortion to this input
 port: "autocomplete" + input.name,
 dataType: options.dataType,
-               url: options.url,
+               url: url,
 data: $.extend({
 q: lastWord(term),
 limit: options.max
 }, extraParams),
 success: function(data) {
 var parsed = options.parse && options.parse(data) || parse(data);
-                   cache.add(term, parsed);
+                    if (typeof options.url != "function") {
+                        cache.add(term, parsed);
+                    }
 success(term, parsed);
 }
 });

You can also download the patch file here:  jquery.autocomplete.js.patch

Now, what if you are using this autocomplete from Devbridge?  You can almost do it out of the box, here is a code sample.


$("input[name*=phone_number]").each(function(i) {
 var prefix = this.id.replace(/\.[^.]*$/, "");
 $(this).autocomplete(
 {
 serviceUrl:baseURL + '/lib/findUsers',
 zIndex: 9999,
 deferRequestBy: 0, //milliseconds
 noCaching: true,
 params: {
 'area':function() { return $(jq(prefix + ".area_id")).val(); },
 'prefix':prefix
 },
 onSelect: function(value, data){  // NOTE: 'this' is NOT defined correctly here
 // do stuff with data
 }
 }
 );
 });

You will notice that I included a parameter that isn’t supported, that is the noCaching parameter.  I had this working pretty good without it, except if you changed the non-autocomplete field (in this case area code), and you go back to the auto field and fail to find something, that is cached with the query, so when you change the area code, you get stuck because the query field got cached, and auto thinks that it should not try again.  That is why I made this tiny patch to this version of autocomplete.


Index: jquery.autocomplete.js
===================================================================
RCS file: /opt/Repository/MobilSense/MobilSentry/Products/MobilSentry/Src/CSS/share/assets/jquery.autocomplete.js,v
retrieving revision 1.1
diff -u -r1.1 jquery.autocomplete.js
--- jquery.autocomplete.js  10 Jan 2010 06:46:45 -0000  1.1
+++ jquery.autocomplete.js  15 Jan 2010 23:20:55 -0000
@@ -230,6 +230,9 @@
 },^M
 ^M
 getSuggestions: function(q) {^M
+      if (this.options.noCaching) {^M
+        this.clearCache();^M
+      }^M
 var cr, me;^M
 cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];^M
 if (cr && $.isArray(cr.suggestions)) {^M

And you can download it jquery.autocomplete.js.patch.

, Hide

One of the most annoying things with javascript is trying to see what is inside of an object.  In python you simply print (‘attributes=%s’%dir(obj)), and in php you simply use var_dump(obj), or if you want to format it into a string, you can use echo “attributes=” . var_export(obj) ;  But with Javascript I really haven’t had an easy way to introspect the attributes of an object.  Until now.

I have been using a great tool for debugging javascript called FireBug, it is a plugin for firefox.  So, firebug has a way to do object introspection via the DOM tab.  When you get an object that you want to analyze simply do something like this in your code (at a global level) var MYOBJECTREFERENCE = new Object();  Now, wherever you have access to that object you want to introspect (in an event handler or whatever), you simply say MYOBJECTREFERENCE.XYZ = obj;  Then, refresh, trigger whatever event it took to generate obj, and then look in firebug’s DOM explorer window for MYOBJECTREFERENCE.XYZ.

YAY!  Now there is an easy way to introspect objects in javascript.  If you know of other ways to do this, please post them for us all to see.

Eric

UPDATE: 12/8/2009

I found another way to do this.  The code is from RefactorMyCode.com .  Mine is a little different because I was getting errors and I had to protect against them a bit… Here you go!


function odump(obj, depth, max) {
 depth = depth || 0;
 max = max || 2;

 if (depth > max)
 return false;

 var indent = "";
 for (var i = 0; i < depth; i++)
 indent += "  ";

 var output = "";
 for (var key in obj){
 // skiplist
 if (key == "domConfig" || key == "selectionStart" || key == "selectionEnd" || key == "schemaTypeInfo") {
 output += "\n" + indent + key + "**: ";
 } else {
 try {
 output += "\n" + indent + key + ": ";
 switch (typeof obj[key]){
 case "object": output += odump(obj[key], depth + 1, max); break;
 case "function": output += "function"; break;
 default: output += obj[key]; break;
 }
 } catch(err) {
 alert("add key=" + key + " to your skiplist because of: err=" + err);
 }
 }
 }
 return output;
}

Hide

Nov/09

24

Javascript for Loops

I had to write something today in javascript that used for loops.  No big deal, but usually I put it into a separate .js file, in this case I had to put it right there in the html.  This created a little problem that I thought I would write about to help remind myself and provide a little guidance to others.

Less Than ‘Test’ In HTML

The problem arises when the html parser gets involved and runs into the javascript which was supposed to be ignored.  Usually I will put almost all the javascript into a separate .js file so that things are cleaner, but in this case, I just need to do a quick loop right in the html.  So, I used a <script tag.  Unfortunately for me, the i<n loop invariance test (the end of loop test) uses a symbol (<) which is the start of an html tag open or close.  I don’t know if this problem occurs when using a simple html file or not, but I am using xhtml and it really broke things.

Here is the header of my xhtml file.

<?xml version="1.0" encoding="utf-8" ?>
<!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" xml:lang="en"  lang="en">

Here is my for loop code.

<script type="text/javascript">
for (var i=0; i<10; i++) {
    alert("test: " + i);
}
</script>

Well the xhtml parsing freaks out when it sees the ‘i<10′ part, because < is obviously looking similar to a tag opening or closing. So at first I tried to put an html comment around it using <!– XXX –> but then my javascript wasn’t even being executed. So I had to eventually use a CDATA section like this.

<![CDATA[

for (var i=0; i<10; i++) {
    alert("test: " + i);
}
]]

This was a good solution that worked for me.

Once I got the loop working, I encountered another problem.

Iterating Over Arrays Can Be Weird

In Java or C or C++ or python etc, we typically iterate over each item in an array and index with a counter. We just stop looking when the index has reached the max number of elements (minus 1) in that array.

In javascript things are different because arrays are really objects with properties. Therefore if you are trying to use the .lenght attribute (like java) you may be surprised. What I found was that

I was getting as the last item in the array an ‘undefined’ element.

for (var i=0; i<all_inputs.length;i++) {
    alert("input: " + i + ")  " + all_inputs[i]);
}

So, the solution is to do everything the same except for the loop invariance test.  Here we just say to loop while the i’th element is not undefined. In other languages, you know that this will generate a array out of bounds type exception, but since this is really checking properties of an object, things are a little different.

for (var i=0;undefined != all_inputs[i];i++) {
    alert("input: " + i + ")  " + all_inputs[i]);
}

And, those are just some handy things to remember next time you are making for loops in your html code and iterating over array elements.

  for (var i=0; i<10; i++) { alert("test: " + i); }  

Hide

Apr/09

25

Javascript Unit Testing

Javascript Unit Testing
======================

http://ajaxpatterns.org/Browser-Side_Test

Hide

Here are some javascript references

Javascript
============

http://www.c-point.com/javascript_tutorial/javascript_keyword_list.htm

http://www.quirksmode.org/js/this.html

How do you make classes and objects in javascript?

http://www.phpied.com/3-ways-to-define-a-javascript-class/

Javascript shell

http://www.billyreisinger.com/jash/

Hide

Find it!

Theme Design by devolux.org