0

I am trying to restrict user's input if user is trying to type some characters (like space). To do so I found this post.

But I wanted to make it through HTML's onkeypress attribute. And faced with problem, that if I specify function to return false, then nothing will happen, but if I return false right in HTML's attribute - input won't happen.

I can't understand what am I doing wrong. Can you please tell me how to solve this?

function doMatch() {
  return false;  
}

$('#test').keypress(function() {
  //return false;   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" onkeypress="doMatch();" id="test"/>
Community
  • 1
  • 1
iwazovsky
  • 1,919
  • 3
  • 20
  • 35

2 Answers2

1

But I wanted to make it through HTML's onkeypress attribute.

I recommend you to not do that, since it's better to keep the Javascript behavior out of your HTML code. The name os this technique is Unobstrusive Javascript.

But if you really want to do that, you must use the return keyword to make it work:

<input type="text" onkeypress="return doMatch();" id="test"/>
Buzinas
  • 11,597
  • 2
  • 36
  • 58
0

You just need to add return before doMatch();

function doMatch() {
  return false;  
}

$('#test').keypress(function() {
  //return false;   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" onkeypress="return doMatch();" id="test"/>
Ripun
  • 210
  • 5
  • 16