1

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.

7
  • what you trying to do in second last line ? it seems if is missing but again what is that && return false ..is it typo ? Commented Jul 27, 2016 at 0:50
  • 1
    1. the second sample is ugly. 2. return !(charCode > 31 && (charCode < 48 || charCode > 57)); 3. The && operand must be an expression not a statement Commented Jul 27, 2016 at 0:51
  • @zerkms it works, thanks! Commented Jul 27, 2016 at 0:57
  • Not what you're asking, but you know the code shown doesn't actually stop the user entering non-numeric data into that input, right? (Because the keyboard isn't the only option for editing...) Commented Jul 27, 2016 at 0:59
  • @nnnnnn i didnt think about it but you are right, im doing this: window.onload = function() { var myInput = document.querySelector('.rows'); myInput.onpaste = function(e) { e.preventDefault(); } } Commented Jul 27, 2016 at 1:13

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Btw, return charCode <= 31 || (charCode >= 48 && charCode <= 57);
1

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.