I’m sorry if maybe the question it’s a bit wide guys, but I’ve tried everything and I can’t came with something to replace this (this is not mine, I’m just using it):
function onlyNum(evt){
evt = window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
// this INPUT will not accept anything but numbers now.
<input type="text" id="idInput" onKeyPress="return onlyNum(event)">
with this:
function onlyNum(evt){
evt = window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
// this INPUT's with this event listeners will just acept numbers now.
// like this code is cleaner since you just need to make a list of ids that will have this listeners.
var input = document.getElementById('idTest');
input.addEventListener('keyDown', onlyNum, false);
I can’t find a way to pass the event to the function and the “return” part. Sorry I don’t even know how to describe it and maybe that’s why I cannot find any info about this problem…
When using generic event handlers with
addEventListener()orattacheEvent(), you can’t justreturn falseto prevent the default action like you can if you put the event handler in the HTML. Instead, you need to callevt.preventDefault()and perhapsevt.stopPropagation()in most browsers or setwindow.event.returnValue = falseandwindow.event.cancelBubble = truein older versions of IE.To do that simply and cross platform, I’ve developed an
addEvent()function that does all the cross platform work for you (including IE6, IE7, IE8). So, using that to add the event handler, all you would do is this:Working demo: http://jsfiddle.net/jfriend00/2ATmz/.
Here’s your code using the new event function:
And, here’s the cross platform event function:
Note: I slightly modified
onlyNum()because this event handler function always passed the event object (you don’t have to handle things differently for IE).