JavaScript


25
Jan 08

Call Javascript function on pressing ‘Enter’ key

In most of the search pages you might have noticed how you can type your queries into the search box and search by pressing the enter key instead of having to click the ‘Search’ button present in the page.

Wondering how to do it? Well, wait no more. Implement the same feature in your pages too.

All we need to know is the key code for the enter key which happens to be ’13′.

Then under the event onKeyDown we can call the javascript which submits the page.

Go through the example below and you’ll know it all.

{

<input type=”text” onKeydown=”Javascript: if (event.keyCode==13) Search();”>

<input type=”button” value=”Search” onClick=”Search();”>

}

The above code will display a text box followed by a button labelled Search as shown in the figure below:(Note: Click on the thumbnail to view)

Search On enter key press

You’ll notice that the onClick event of the Search button calls a javascript function named Search(). To have the same function called on pressing the enter key when the cursor is in the text box, we check if the keycode is 13 and subsequently call the Search() function.


14
Jan 08

Escape single quotes(‘) in JavaScript

There may be instances where you need to display single quotes in an alert box. Or may be double quotes too. To have these displayed without any errors all you need to do is add a backslash “\” before the single quote or double quote. That’s it!!!

Example: alert(“Hi! Welcome to my \’blog\’. This can also be displayed as \”blog\”.”);

The output in the alert window will be:

Hi! Welcome to my ‘blog’. This can also be displayed as “blog” .


26
Dec 07

ReplaceAll for JavaScript

Unlike java code, JavaScript doesn’t have an exclusive “replaceAll” function. But that doesn’t mean the functionality’s absent in javaScript.

To replace all the occurrences of a particular character or string in a given string we make use of the letter ‘g’ which implies to replace all the occurrences of the given letters.

Ex. var stringToPerformReplace = “3+5-1+2″;

var replacedString = stringToPerformReplace.replace(“+”,”-”,”g”);

The new String will be “3-5-1-2″.

In a similar manner instead of “g”, if you specify “i” it implies “ignorecase”.

Note: You can club both together i.e. “gi” is valid.