Reputation: 1581
I am using a keypress
event
and I want to get the value
within the input
box after a key has been pressed. I also would like to capture which key has been pressed. In this example I am only allowing the user to enter numbers into the input
box (I know there is a number
type
for inputs). I am using setTimeout
to get the value
from the input
box. Is there a better way to accomplish this? Would this ever fail?
var elTest = document.getElementById('test');
var elResult = document.getElementById('result');
function isNumber(evt, el) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
evt.preventDefault();
return false;
}
setTimeout(function () {
elResult.textContent = el.value;
}, 0);
return true;
}
elTest.addEventListener('keypress', function(e) {
return isNumber(e, this);
});
<input id='test' />
<div id='result'>
</div>
Upvotes: 0
Views: 4787
Reputation: 571
I would go with a combination of keydown and keyup event listeners due to the fact that the keypress event doesn't fire on backspace or delete.
On keydown, check for number, backspace/delete input and prevent if needed.
On keyup, update the result output from the input value.
var elTest = document.getElementById('test');
var elResult = document.getElementById('result');
function allowInput(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
var isNumber = charCode < 58 && charCode > 47;
var isBackspace = charCode == 8 || charCode == 46;
return isNumber || isBackspace;
}
elTest.addEventListener('keydown', function (e) {
if (!allowInput(e)) {
e.preventDefault();
return false;
}
return true;
});
elTest.addEventListener('keyup', function (e) {
elResult.textContent = this.value;
});
Upvotes: 1
Reputation: 437
I think you just got the event and this objects mixed during the function call. If you use this.value, then the the number won't be there yet, but if you use the event.key (which gives the string value of the key) then you should get the proper output.
var elTest = document.getElementById('test');
var elResult = document.getElementById('result');
function isNumber(evt, el) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
evt.preventDefault();
return false;
} else {
elResult.textContent += evt.key;
}
return true;
}
elTest.addEventListener('keypress', function(e) {
return isNumber(e, this);
});
<input id='test' />
<div id='result'>
</div>
Upvotes: 1