can some one explain me that line by line

$("#amount").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
5 Years
Discussion Span
Last Post by MartinRinehart

$ - name of several different functions, much abused by libraries. Best known: jQuery, where it is an equivalent to a CSS selector. Assuming that's the one, '$("#amount") selects the DOM element whose ID is "amount".

$xxx.keydown - "call me if there is a keystroke while I have focus"

keydown( function(event) { ... } ); - note carefully how the parens and braces nest. Use a pencil on a listing at first. This is an anonymous function. It will be called on a 'keydown' event on the selected object. 'event' is the parameter that will be passed to this code. (MSIE doesn't pass this parameter. I assume this is a library that covers over this problem, always passing the param.)

In the function, 'event.keyCode' is the number assigned to each key on the standard keyboard. Plug an 'alert( event.keyCode )' into the first line of the function and watch what happens when you type keys. Is 8 a backspace keystroke?

The last line, 'event.preventDefault()' calls a method of either MSIE, or everyone except MSIE (I forget - you test) that says "this keystroke has been handled; no further processing, thank you."

Hope this gets you on your way.


i have another question that why shouldn't we use key-up instead of key-down..in this example and basically what is the mainly difference between these two.

according to my knowledge key-up isn't used because it executes while the key is released and key-down executes while key is pressed

Edited by extemer: n/a


Keydown lets you use what used to be called the "typematic" feature: hold the key down and it repeats.

Look up "keypress", too.


P.S. You're welcome.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.