I have a page wherein a user can click a button to post something. This works in a similar fashion as facebook.
When the user presses enter, the post will automatically be saved and displayed. When the user presses shift and enter, I was expecting a new line but it doesn't seem to work. I am using JQuery for that function. What could be wrong with this code ? I saw this solution while researching.
$("#someTextArea").keypress(function(event){
if(event.which == 13 && !event.shiftkey) {
// ajax
}
});
Try using event.keyCode and event.shiftKey(capital K [camel-case]);
For your task something like this should do:
var Keys = {
ENTER: 13
};
$("#someTextArea").keypress(function (event) {
if (event.keyCode == Keys.ENTER) {
if (event.shiftKey) {
// make a new line
} else {
//submit the text
}
}
});
Related
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');
}
}
})
I am trying to build a comment section that allows instant preview on the front end.
Everything worked fine except the behavior after submitting the comment.
In my code, I trigger the submission of the comment when the user press the Enter key in the textarea, then clear the textarea by resetting the value.
However, even after I disabled the default behavior of the enter key by declaring e.preventDefault(), a new line is still inserted when enter is pressed repeatedly.
Also, even after I check the length of the value of the textarea before submitting, my code accept comment with only / '\n' as valid content and hence the user will be able to submit 'empty' comment if they press enter in the textarea multiple times...
Please help, I cannot think of a solution and I am considering to add a post button where the user has to manually click it to submit...
My code on fiddle:
http://jsfiddle.net/8ve0gLab/2/
My code:
$(document).ready(function(){
$('#comment-input').keydown(function(e){
var commentContent = $(this).val()
if (e.which == 13) {e.preventDefault()}
if (e.which == 13) {
e.preventDefault()
if (commentContent.length != 0) {
$('#comment').append(commentContent)
$(this).val('')
}
else {
alert('Comment is empty')} /*This line is not working properly*/
}
})
})
Try change your code to
$(document).ready(function(){
$('#comment-input').keydown(function(e){
var commentContent = $(this).val();
if (e.which == 13) {
if (commentContent.trim()){
$('#container').append("<p>"+commentContent+"</p>");
$(this).val('');
}
else {alert('Area is empty');}
}
})
})
notice the ".trim()" which is a javascript string method.
you can try in the jsfiddle here : http://jsfiddle.net/xdxqwLof/
This may address your issue:
if (event.keyCode == 10 || event.keyCode == 13){
event.preventDefault();
}
JS Fiddle Demo
I'm attempting to create a Greasemonkey script that can submit a tweet when a user hits the 'enter' key. I've gotten this to work fine on a simple HTML page (with the help of a few excellent tips on this site). However, when I try to use the code on my twitter page, the alert only fires if a tweet is not currently being authored.
document.onkeyup = function(event){
var keyCode;
if (window.event) // IE/Safari/Chrome/Firefox(?)
{
keyCode = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyCode = event.which;
}
if (keyCode == 13){
alert("Enter pressed");
}
}
My next thought was to test for a more specific keypress event. So I tried testing for a key event within the new tweet textarea:
document.getElementsByClassName("twitter-anywhere-tweet-box-editor")[0].onkeyup = function(event)
...but this event never seems to fire. I also tried grabbing the element by tag:
document.getElementsByTagName("textarea")[0].onkeyup = function(event)
...but not dice there either. I wonder if this has to do with the fact that the new tweet window is not loaded from the get-go at window.onload(). Thoughts?
I got it thanks to this post. I've also posted the full Greasemonkey script here.
setInterval (function() { checkForTweetbox (); }, 500);
function checkForTweetbox () {
var tweetbox = document.querySelector ('div.tweet-box textarea'); //check for new tweet window
if (tweetbox) {
if (! tweetbox.weHaveProcessed) {
tweetbox.weHaveProcessed = true;
// alert ('New tweet-box found!');
}
}
tweetbox.onkeydown = function(event){
if(event.keyCode == 13){ //13 = Enter keycode
document.querySelector ('a.primary-btn').click(); //there must be at least one character in the textarea
}
}
}
I have the following simple <textarea>
<textarea id="streamWriter" rows="1" cols="20" placeholder="Writer"></textarea>
Also I have the following jQuery/JavaScript code block:
$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
alert('ctrl enter - go down a line as normal return would');
return true;
}
e.preventDefault();
alert('submit - not your default behavior');
}
});
I'm trying to force the not to create a new line break on normal return keydown. But I want this behavior if Ctrl+Enter was typed instead.
This does detect the difference but is not forcing the behavior that I need.
If you've used Windows Live Messenger, I need the same textbox behavior. Enter to submit (In my case I will call a function but stop the textarea from going down a line) and Ctrl+Enter go down a line.
Solutions? Thanks.
Update:
$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
//emulate enter press with a line break here.
return true;
}
e.preventDefault();
$('div#writerGadgets input[type=button]').click();
}
});
The above does what I am trying to do. There is just the part to emulate enter press with a line break. Please let me know how to do this if you know.
Using keypress instead of keydown works a little better, however will not work with the Ctrl key; I switched to the shift key - jsfiddle.
Edit: As far as I can tell, you won't be able to use Ctrl key consistently cross browser because the browser uses it for it's own short-cuts. You would run into the same situation with the alt key.
Edit again: I have a solution that works with the Ctrl key - jsfiddle.
$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode === 13 && e.ctrlKey) {
//console.log("enterKeyDown+ctrl");
$(this).val(function(i,val){
return val + "\n";
});
}
}).keypress(function(e){
if (e.keyCode === 13 && !e.ctrlKey) {
alert('submit');
return false;
}
});
Edit: This doesn't work 100%, it only works if you are not in the middle of text. Gonna have to work on a way to have the code work on text in the middle.
By the way... Why are you doing it this way? Wouldn't it be confusing to the user if they pressed enter to make a new line and the form all of a sudden submitted before they were ready?
Clear VanillaJS:
document.querySelector('#streamWriter').addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
// Ctrl + Enter
if(e.ctrlKey) {
console.log('ctrl+enter');
// Enter
} else {
console.log('enter');
}
}
});
Kevin B's solution works well on Mac, but not on windows.
On windows, when ctrl +enter is pressed, the keyCode is 10 not 13.
Ctrl+Enter jQuery in TEXTAREA
I want to have a chat box (textarea) where if user press Enter then it should submit the chat, and if user press Shift+Enter then it should enter in a new line.
I tried something but not able to figure out the exact keyup or keydown thing. The code I'm using at the moment is:
$("textarea").keydown(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
}
});
jsFiddle
Also I want to get the \n in place when Enter+Shift key is pressed.
EDIT
Issue with my code is:-
When i am check the content on client using using alert then it shows the next line. But when i am posting it my rails back end. Then its just a simple string. No new line thing is there.
This is how i am sending chats to rails server.
$.post("/incomingchat", { body:$("#chat_" + group_id).val() },
function(data){
// do something..
});
I've answered this before. It's a little tricky if the caret is not at the end of the textarea:
How do I detect "shift+enter" and generate a new line in Textarea?
$("textarea").keydown(function(e)
{
if (e.keyCode == 13)
{
if (e.shiftKey) {
$(this).val( $(this).val() + "\n" );
}
else {
submitTheChat();
}
}
});
Consider using the keypress event instead. If you run the code in jsfiddle, you'll see that a new line is not added when you press enter.
$("textarea").keypress(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
//now call the code to submit your form
alert("just enter was pressed");
return;
}
if (e.keyCode == 13 && e.shiftKey)
{
//this is the shift+enter right now it does go to a new line
alert("shift+enter was pressed");
}
});