I need to find continuous enter key pressing in jquery. Is this possible?
$('#password-input').keyup(function(e) {
if (e.which == 13) {
alert("Enter key")
}
});
Here If I am pressing ENTER key more than one time mean I am getting alerts for two times. But i need to get only one time only.
Please help me!
You can use jQuery#bind to bind the keyup event and than unbind the keyup event with jQuery#unbind when the end user pres the "Enter key" in order to prevent multiple times the "Enter key":
var $passwordInput = $('#password-input');
$passwordInput.bind('keyup', function(e) {
passwordInputKeyupHandler(e);
});
function passwordInputKeyupHandler(e) {
if (e.which === 13) {
console.log('Enter key!');
$passwordInput.unbind('keyup');
return setTimeout(function(){
console.log('Rebind keyup event');
$passwordInput.keyup(passwordInputKeyupHandler);
}, 2000);
}
console.log('Any other key...');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password-input" type="password">
Note that as pointed out by #dorado on the comments was made a 'rebind' after 2 seconds, using setTimeout(), in order to avoid the end user to have to make a page reload..
Besides using a variable to store the state I suppose you will also want that if a few milliseconds have passed, then pressing enter key again gives you an alert. This can be achieve by setTimeout. For example, here the enter key will be re-detected only if it is pressed after an interval of 2000ms.
var pressed = false;
$('#input-element').keyup(function(e) {
if (!pressed) {
if (e.which == 13) {
pressed = true;
alert('Enter pressed.');
i = setTimeout(function() {
pressed = false;
}, 2000);
}
}
});
Use a variable to store the state
var pressed = false;
$('#password-input').keyup(function(e) {
if (!pressed) {
if (e.which == 13) {
pressed = true;
alert('Enter key');
}
}
});
Use .setTimeout() to set delay for display alert. In delay time, if enter key pressed again, remove previous timeout and set new timeout. At the end of timeout, display alert.
var interval;
$('#password-input').keyup(function (e) {
if (e.which == 13) {
clearInterval(interval);
interval = setTimeout(function(){
alert("Enter key")
}, 500);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password-input" />
You can change time of delay to your custom time.
var pressed = false;
$('#password-input').on('keyup',function(e) {
if (e.which == 13 && !pressed) {
pressed = true;
alert("Enter key");
}
});
Related
I need the script for functioning the window.location only after pressing the ENTER key 3 or n times.
This is my current code and i am trying to modify it. Need help, still.
function KeyPress(f) {
var event = window.event? event : f
if (event.keyCode == 13)
window.location = './index.html';
}
document.onkeypress = KeyPress;
Following your instructions, after three press to the key ENTER, it should run the code that will call window.location. In this example, I'm using console.log to prove it is doing what you asking.
Note: When you run it, you need to click with the mouse where it says "Press Enter 3 times.". In this way, the browser will focus on that section. Then, you can press the ENTER key three times.
document.addEventListener("keyup", (e) => enterKeyPressed(e))
let counter = 1;
function enterKeyPressed(event) {
console.log("Key", event.keyCode, " Pressed:", counter);
if (event.keyCode == 13 && counter == 3) {
console.log("Enter key is pressed");
// window.location = "<url you want to go>";
return true;
}
counter++;
return false;
}
Press Enter 3 times.
Check the log.
So I'm trying something out, if you have two functions you want to call after the same key press like so:
var plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
plus();
var minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
minus();
function check() {
document.addEventListener("keyup", function(e) {
if(plus) {
if (e.keyCode == 13) {
console.log("enter pressed after plus");
plus = false;
minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
}
} else if(minus) {
if (e.keyCode == 13) {
console.log("enter pressed after minus");
minus = false;
plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
}
}
});
}
check();
If you press minus first then enter console.log("enter pressed after plus") always gets called first because of the code's order, even though what I want to do is that I want the enter to correspond to the key I'm pressing first, if I press plus first then I want console.log("enter pressed after plus") to get called, and if I press minus first then I want console.log("enter pressed after minus") to get called.
Any help would be appreciated and thanks in advance.
Oh also sorry about the stupid title, couldn't think of a better one.
To clean this up a bit (keep it DRY) you can move all the event handler logic into a single function and use a single listener.
To keep track of the last pressed key we can use a variable defined in the function's outer scope. And, update it after each event. Then, when "Enter" is pressed we can check what the last key was and log accordingly.
Also, the KeyboardEvent.keyCode property is depreciated. You should use KeyboardEvent.code property instead.
Example
const input = document.querySelector('input')
const log = document.getElementById('log')
function check() {
let lastKey = null
input.addEventListener('keyup', ({ key }) => {
if (['+', '-', 'Enter'].includes(key)) { // we only care about these keys
if (key === '+') log.textContent = 'plus'
if (key === '-') log.textContent = 'minus'
if (key === 'Enter') { // `Enter` was keyed, what was keyed last?
if (lastKey === '+') log.textContent = 'enter pressed after plus'
if (lastKey === '-') log.textContent = 'enter pressed after minus'
}
lastKey = key // current key becomes last key
}
})
}
check()
<input placeholder="Click here, then press and release a key." size="40">
<p id="log"></p>
This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
How do I make so that when the enter key is pressed multiple times, the site only detects the input once? I have a small bug which occurs whenever the user double taps the enter key in an input box, so what I want to do is only accept the input press once. Thank you so much in advance!!
$('#search_list').keypress(function(e) {
if (e.which == '13') {
}
}
You can prevent repeatedly enter pressing by this way:
var enterPressed = false;
$('#search_list').keypress(function(e) {
if (e.which == '13') {
if( ! enterPressed){
// do some processing
return;
}
enterPressed = true;
setTimeout(function(){
enterPressed = false;
}, 1000);
}
}
Inspired by this post.
var enterPressed = false;
$('#search_list').keypress(function(e) {
if (e.which == '13') {
if( ! enterPressed){
// do some processing
enterPressed = true;
setTimeout(function(){
enterPressed = false;
}, 1000);
}
}
}
I think this way is better.
I have this function where #text_comment is the ID of a textarea:
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
}
});
What is happening is the text is appending when the enter/return key is hit (keyCode 13), but it is also moving the text a line down, as the enter/return key is supposed to.
This is occurring even though I set the value of the textbox to "".
How about event.preventDefault()
Try and stop your event propagation (See http://snipplr.com/view/19684/stop-event-propagations/) when entering the if(e.keyCode == 13) case.
try this one event.stopImmediatePropagation()
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
e.stopImmediatePropagation()
///rest of your code
}
});
I've tested this out, this works. The enter does not create a new line.
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
return false;
}
});
Although I am wondering, if you don't want to ever have a new line, why are you using a textarea, why not use a input type='text' instead ?
Answer here http://jsfiddle.net/Z9KMb/