I have this HTML text input as below:
<label style="color: white;" for="id">ID:</label>
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" maxlength="9" name="id" id="id">
Now, in the onkeypress I successfully added so only numbers can be entered. but I have a JavaScript function called:
function checkID() {
and I want that additionally, after every number entered it will call this function. But I just can't get it to do them both (only allow numbers and call the function).
Thanks in advance! Itay.
You should understand how HTML works and how browsers call and execute JavaScript functions.
<input type="text" ... />
You told the browser to allow all sort of values to be put into the input element.
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
In your HTML snippet, you tell the browser to call and run JavaScript; testing if the event character code of the current key is between 48 and 57. The JavaScript code is valid, and it will return true or false. Whenever your JavaScript code returns false, the browser won't allow the last pressed key the pass as a value for the HTML <input /> element.
Here is the fix.
The input type should be number to allow only numbers as input. onKeyPress=checkID() will invoke your function. By doing so you delegate the input checks up to the browser and get your checkID() function into play.
Or if you really need to control key press events by yourself, because checkID() will be called on every single button press anyways, you could put the character code check at the top of your checkID() function.
Always separate markup/layout (HTML) from business/controller/dynamic logic. In other words - never write JS in HTML and never use on-attributes.
Same goes to styles. Never use
styleattribute. Use CSS instead.Whenver you want multiple event listeners added use node.addEventListener('eventname', handler)
However, in your case you, probably, you want to call checkID as a part of your validation logic in the same event listener.
Create a JS file, for example
app.jsand add before</body>-<script src="app.js"></script>var input = document.getElementById('id'); input.addEventListener('keypress', function (event) { if (event.charCode >= 48 && event.charCode <= 57) { checkID(input.value); return true; } else { return false; }); // you can add as many listeners as you want // they all will be called in the order you attached them // however, different event handlers should be absolutely independent // and shouldn't know about each other. If you need to do something within one flow, // then do everything in one handler input.addEventListener('keypress', handler2); // ...