I have an input field that I have bound an event on keypressed, but when I press Enter (to execute the event for the input) two dialogs from jQuery UI pops open and ruin my variables. How can I stop the events bound to the enter key for dialogs?
$("#itemSample").on('keypress', function (e) {
if (e.keyCode == 13 && $("#itemSample").val().trim().length > 0) {
//do something
}
});
On the parameter 'e' (Event) you have the necessary functions:
$("#itemSample").on('keypress', function (e) {
if (e.keyCode == 13 && $("#itemSample").val().trim().length > 0) {
// You probably need just one of the following two lines:
e.preventDefault();
e.stopPropagation();
}
});
For more info: http://css-tricks.com/return-false-and-prevent-default/
Related
I have a text area. Each time the enter key is entered the cursor travels to the next line of the text area and a function is called. This function posts/updates the entry in a database. I want it so that if I edit a line and then click on the mouse to resume typing at another line the function is again called on the mouse click
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
Is it possible to change my line to something like this and the method gets called on pressing the enter key or pressing the mouse(anywhere in the text area)?
if (e.keyCode == 13 || mouse.click) {
I know the above isn't correct but want to illustrate what I'm after
You could take use of jQuery's .on method like so:
$("#textarea").on('click keydown', (e) => {
if(e.keyCode && e.keyCode == 13 || e.type == "click" ){
// Do stuff
}
});
It takes a first parameter as string with different events, which mean you can listen to multiple events at once. The second is a callback function, where you can track the event that is triggered. Nb: Events are different between click and keydown. You can have a closer look by putting console.log(e); in your callback
You'll need to attach another event listener. The keydown event will not trigger when a mouse is clicked. You will need to add a $(...).click(function ...) as well. For example...
function myFunction (e) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
stream();
}
$("#textarea").keydown(function() {
if (e.keyCode == 13) {
myFunction()
e.preventDefault();
}
});
$('#textarea').click(myFunction)
Instead of putting a condition you can create 2 events and a common function to handle it.
Foe Example:
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
logic1()
$("#textarea").click(function() { logic1();});
function logic1(){
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
}
I don't know about jQuery but with vanilla JS you can do something like this:
const textarea = document.querySelector('textarea');
const foo = event => {
const output = document.querySelector('output');
output.textContent = event.type;
}
textarea.addEventListener('click', foo, false);
textarea.addEventListener('keypress', foo, false);
<textarea></textarea>
<output></output>
I want to capture "enter" and "blur" on a form field. If I hit "enter" and "tab", it will also trigger the blur event... Only one trigger, so "OR" not "AND.
$('#login-input-password').bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
});
answer accepted implemented
FUNCTION usage
function bindTriggerEnterOrBlur(selector,myFunction)
{
$(selector).bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
if (!$(selector).data('has-triggered')) {
$(selector).data('has-triggered', true);
// do something only once, not twice
myFunction();
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
}
});
$(selector).bind('focus', function(e){
$(selector).data('has-triggered', false);
$(selector).select();
});
}
CALL to FUNCTION
bindTriggerEnterOrBlur('#login-input-email',submitLoginEmail);
Where submitLoginEmail is the function that does something for the trigger, e.g.,
function submitLoginEmail()
{
// submit on enter...
var email = $("#login-input-email").val();
if(validEmail(email))
{
submitNextLogin();
}
}
If I am getting your requirement right, you want to execute the callback only once but currently it is getting executed twice.
If that is the case then you will need some way to indicate if the callback has been called already.
One way would be to use data attributes
$('#login-input-password').bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
if (!$(this).data('done') {
$(this).data('done', true);
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
}
});
You will also need another event handler to reset the done attribute of the element
$('#login-input-password').bind('focus', function(e) {
$(this).data('done', false);
});
You are doing an OR. You want a XOR (Exclusive OR), which has to be done using a combination of comparisons.
if (( (e.type == 'blur') && !(e.keyCode == 13)) ||
(!(e.type == 'blur') && (e.keyCode == 13))) {
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
You want to prevent the script from firing again though, so you'll need to do even more state comparison to make sure your asynchronous event handler knows that the blur or keypress events have occurred and ensure the handler doesn't run twice.
You can also do something like:
var doo = function(e){ console.log("do..."); }
$('#wmd-input').bind('blur', doo);
$('#wmd-input').bind('keypress focus', function(e) {
$('#wmd-input').off('blur');
if (e.keyCode == 13) {
doo(e);
} else
$('#wmd-input').bind('blur', doo);
});
And it does bind again when focus happens.
I am trying to develop my webpage where I have a simple input field where I can type something. I want that when I type something and press "enter", a function gets called. The code I am using is:
$(document).ready(function(){
$("#searchBar").click(function(){
$("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$("#searchBar").bind("enterKey", function (e) {
searchFunction();
});
})
})
Something is not working well. I have 2 questions:
First of all by debugging on the browser I realize that the event "keyup" is called whenever I type any kind of character, but not when I press "enter" and I don't know why.
By always debugging and using a breakpoint on the keyup handler, it happens that when I press a key, in order to get out from the breakpoint I have to resume the script execution once.. then if I type another character and I go again at the breakpoint, I have to resume the script exectuion twice instead of once to continue debugging.. and so on incresing.. why do I have this kind of behavior?
Thanks in advance!
Two problems:
#searchBar only listens to keyUp and Enter if you have clicked on it at least once
#searchBar adds a new keyUp and Enter listener for each time it receives a click event
I'd just bind the events once like so:
$(document).ready(function(){
$("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$("#searchBar").bind("enterKey", function (e) {
searchFunction();
});
});
I can't come up with a valid reason to stop listening to the events, but if that's what you want, then I'd unbind just before or after the call to your searchFunction();
$(document).ready(function(){
$("#searchBar").click(function(e){
$(this).keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$(this).bind("enterKey", function (e) {
searchFunction();
$(this).unbind("enterKey");
$(this).unbind("keyup");
});
});
// but you'd also need to unbind the events if the user clicks somewhere else in the document, otherwise, these events would still get attached every time the user clicks #searchBar
});
But it's unnecessary, as the events are only fired when #searchBar has focus. All these events also detach if you delete #searchBar
Also, why fire "enterKey" when you already are listening for keystrokes?
$(document).ready(function(){
$("#searchBar").keyup(function (event) {
var keycode = event.keyCode || event.which; //this for cross-browser compatibility
if (keycode == 13) {
searchFunction();
}
});
});
I have to resume the script exectuion twice instead of once to
continue debugging.. and so on incresing.. why do I have this kind of
behavior?
You are attaching a new keyup and enterKey event at each click on element.
Remove click event or use .one() to attach click event
$(document).ready(function() {
var search = $("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
search.trigger("enterKey");
}
})
.on("enterKey", function (e) {
searchFunction();
});
})
or, if one click is intended to begin process
$(document).ready(function(){
var search = $("#searchBar").one("click", function() {
search.keyup(function (e) {
if (e.keyCode == 13) {
search.trigger("enterKey");
}
})
.on("enterKey", function (e) {
searchFunction();
});
})
})
I have a submit button, I use $("#submit") to perform "myAction function", but in the same time I also want if the user pressed enter, it perform "myAction function"..
I can't do like this
$("#submit").on('click keyup', function(){
//myAction function
});
because I have to attach the keyup event to my input field instead of #submit..
Give a name to your function and bind both event on the selector. Then add a special condition:
function send(e){
if(e.type == 'click' || (e.type == 'keyup' && e.wich == 13))
}
$('[type=text]').on('keyup', send);
$('[type=submit]').on('click', send);
Write your my action as a separate function and use it as below
function myAction() {
console.log('act');
//do your stuff here
}
$("#submit").on('click', myAction);
$("input.enter").on('keypress', function (e) {
//enter key code is 13
if (e.which == 13) {
myAction()
}
});
Demo: Fiddle
I currently have a textbox that I am invoking a keyboard stroke on focus:
$myTextBox.on('focus', function(e){
$(document).keydown(function(e){
if(e.which==13)
e.preventDefault()
});
$(document).keyup(function(e){
if(e.which ==13)
alert("hey");
});
});
If I click on this multiple times pressing 'enter' once will cause many alerts, how can I avoid this so that only it is only invoked once.
You're adding the event listener every time the field gets focus.
Just add the keydown, keyup listener on the document ready function...
$(function() {
$("#myTextBox").keydown(function(e){
if(e.which==13)
e.preventDefault()
});
$("#myTextBox").keyup(function(e){
if(e.which ==13)
alert("hey");
});
});
http://jsfiddle.net/ShHkP/
Like others have said, you don't have to keep adding the event on focus. As well, you should just attach the event to the textbox itself because that is in fact what you're trying to do when you add the event on focus.
$myTextBox.on({
'keydown': keyDown,
'keyup': keyUp
});
So that your application doesn't go into an enter-alert-ok loop, you have to turn off the keyup listener before the alert() call, and then turn it back on after hitting ok.
Here's a fiddle.
I see what you're trying to do (or not?). You could just attach the event to the form and exclude the textarea instead of adding it to the document everytime the input gets focused.
$('form').on('keydown', function( e ) {
// Prevent submit when pressing enter but exclude textareas
if ( e.which == 13 && e.target.nodeName != 'TEXTAREA' ) {
e.preventDefault();
}
}
var alreadyPressed = false;
$("textarea").keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
alreadyPressed = true
}
});
$("textarea").keyup(function (e) {
if (e.which == 13 && !alreadyPressed) {
alert("hey");
alreadyPressed = false;
}
});
http://jsfiddle.net/DerekL/Dr6t2/