Friday, December 10, 2010

Insert Backslash Before a Double Quote

Sometimes, you need to dynamically write html text from JavaScript. If the text contains a combination of single and double quotes, you may run into problems. Here is a simple function to avoid those problems.
function insertBackslashBeforeDoubleQuote(str){
 var reg = /"/g;
 var newstr = '\\"';
 return str.replace(reg,newstr);
}
As you see, the function uses a RegExp object on the first line to look for a double quote:
reg = /"/g;
 
The second line defines our replacement string - \"
The backslash in front of the quote has to be escaped with another backslash.
newstr = '\\"';
The last line searches the string and if a double quote is found it is replaced by our newstr pattern.
return str.replace(reg,newstr);
Here is a similar function that inserts a backslash before a single quote if it is contained in the string argument.
function insertBackslashBeforeSingleQuote(str){
 var reg = /'/g;
 var newstr = "\\'"
 return str.replace(reg,newstr);
}


Some other posts:

A JavaScript endsWith function

Highlight HTML Table Rows with JavaScript

Wednesday, November 17, 2010

"Event is Not Defined" Error in Firefox

This error may occur when you try to attach a JavaScript function dynamically to page elements and pass an event to the function. An example:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == 'text') {
        inputs[i].onkeypress = function() { return isNumericKey(event); }
    }
};

Here is a listing of the validation function:


/* Numeric Validation */
function isNumericKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode >= 48 && charCode <= 57 || charCode == 46) {
        return true;
    }
    else {
        return false;
    }
}
 
This code will work perfectly in IE and it won't allow users to type any other characters than numeric. However, in Firefox, it will throw an error: "event is not defined".

First solution:

Check whether the event is defined in Firefox and attach a reference to the validation function.

if (typeof (event) == "undefined")
    inputs[i].onkeypress = isNegativeNumericKey;
else
    inputs[i].onkeypress = function() { return isNumericKey(event);}

In this case, the event is a global variable that does not exist in Firefox. We could have rewritten the type check as follows:

if (typeof (window.event) == "undefined") ...

Second solution:

Use the following version of the function call in Firefox by passing the event parameter to the function that handles the keypress event:

inputs[i].onkeypress = function(event) { return isNumericKey(event);}

But this would not work in IE.  The solution: normalize the Event interface in the function body:

function(event) { 
   event = event || window.event;
   return isNumericKey(event); 
}