Reputation: 43
I have this html input:
Rows: <input type="text" class="rows" onkeypress="return isNumber(event)"><br>
and this javascript function to validate only numbers
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
but i want to work with micro-branching to do something like this:
function isNumber(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
(charCode > 31 && (charCode < 48 || charCode > 57)) && return false;
return true;
}
the thing is that the last 2 lines didnt work.
Upvotes: 1
Views: 5099
Reputation: 23840
return
is a statement rather than an expression, and thus cannot be used as argument to a logical operator.
In your case however, the last two lines can be rewritten into a single return
statement, by simply inverting the condition to the if
clause:
return !(charCode > 31 && (charCode < 48 || charCode > 57));
Or, as zerkms notes, you can lose the !
by flipping the operators (&&
<=> ||
and <
<=> >=
), which, in my humble opinion, increases readability:
return charCode <= 31 || (charCode >= 48 && charCode <= 57);
Upvotes: 3
Reputation: 2585
According to your description, it looks like you are looking for conditional check and return :
function isNumber(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
Upvotes: 1