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"/>

2 Answers 2

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

Comments

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"/>

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.