Reputation: 362
I'm trying to create a form, with command which works only if SPACE key is pressed, but in particular input text.
I want that a specific input will be disabled if the user presses on SPACE button inside the input. For example, if the user presses SPACE in First Name
input, the input will be disabled.
This is what I've tried so far:
window.addEventListener("keypress", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.charCode == "32") {
$("input#fn").prop('disabled', true);
}
}
But it works if the user presses SPACE anywhere in the page. My meaning is, if he isn't in the input area and presses SPACE, the FN input is disabled.
I've tried to create a input#fn
variable but I don't know how to use it as argument in a function.
Thanks in advance.
Upvotes: 0
Views: 57
Reputation:
You can try something like this (if you use jQuery):
$('#user_login, #user_pass').on('keydown', function(e) {
if (String.fromCharCode(e.keyCode) == ' ') {
$(this).attr('disabled', 'disabled');
}
});
Upvotes: 1
Reputation: 64526
Assign the event handler to the input only, not the window:
document.getElementById('fn').addEventListener("keypress", checkKeyPressed, false);
Or jQuery:
$('#fn').keypress(checkKeyPressed);
You might prefer to make use of this
in the function, instead of reselecting the input:
function checkKeyPressed(e) {
if (e.charCode == "32") {
$(this).prop('disabled', true);
// or plain JS: this.disabled = true;
}
}
Upvotes: 2