Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
JavaScript
function isNumberKey(evt)
     {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
           return false;

        return true;
     }


this code allows user to input only number in txtbx........
bt I dont know how it works...
please explain me this code in deep....
Posted
Updated 15-Oct-13 1:53am
v2

This code checks the event of key press, mouse down

evt.which :-
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button.
Some browsers use keyCode, others use which.

evt.keycode:-
In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode.


Your this line checks which key pressed on keyboard and it gets ascii no. of that key
var charCode = (evt.which) ? evt.which : event.keyCode

after it validates that charcode with ascii no which is ranging from 0 to 9
 
Share this answer
 
? means ternary operator which run as a if else like condition
this function you can place on textbox like onKeypress="return isnumberKey();"
when you will press a button then a keypress event will call

Suppose if you have press other than numeric value then it will not print anything in your textbox other than numeric value

var charCode = (evt.which) ? evt.which : event.keyCode// Suppose you pressed "A" key then this Ascii value will store in charcode now it will check condition with if (charCode > 31 && (charCode < 48 || charCode > 57)) as this "A" doesnot fall in this range thus it will return false and it will not print any value in textbox

try and letme know
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900