Reputation: 23
I am learning about javascript from the book "JavaScript Bible", but I have some difficulties. I'm trying to understand this code:
function checkIt(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
status = "This field accept only numbers."
return false
}
status = ""
return true
}
Someone can explain to me?
Upvotes: 2
Views: 452
Reputation: 167182
// Create a function named checkIt, which takes an argument evt.
function checkIt(evt) {
// If the user has passed something in the argument evt, take it.
// Else, take the window.event as evt.
evt = (evt) ? evt : window.event;
// Get the Character Code. It can be either from evt.which or evt.keyCode,
// depending on the browser.
var charCode = (evt.which) ? evt.which : evt.keyCode;
// If the Character is not a number, the do not allow the user to type in.
// The reason for giving 31 to 48 and greater than 57 is because, each key
// you type has its own unique character code. From 31 to 48, are the numeric
// keys in the keyboard.
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
// Give a status informing the user.
status = "This field accept only numbers.";
// Prevent the default action of entering the character.
return false;
}
// Clear the status
status = "";
// Allow the user to enter text.
return true;
}
(source: cdrummond.qc.ca)
(source: cdrummond.qc.ca)
PS: I edited your code adding semi-colons ;
which were missing.
Upvotes: 3
Reputation: 1113
it basically says:
evt = (evt) ? evt : window.event
If "evt" is a value, then carry on otherwise assign window.event to evt. This is a shorthand if statement
var charCode = (evt.which) ? evt.which : evt.keyCode
Make a new variable and if a child of evt ("which") exists then assign it to the newly made variable, if not assign "evt" child; "KeyCode"
if (charCode > 31 && (charCode < 48 || charCode > 57)){
status = "This field accept only numbers."
return false
}
if charcode is greater than 31 and charcode is smaller than 48 or bigger than 57, then procede. Assign a string to the var status and returns false which terminates the function ( meaning something went wrong)
status = ""
return true
if all went well in the above statement then assign any empty string to "status" and return true which means everything went well
Upvotes: 0