I have a textarea like this:
<textarea tabindex="1" maxlength='2000' id="area"></textarea>
I watch this textarea with jquery:
$("#area").keypress(function (e) {
if (e.keyCode != 13) return;
var msg = $("#area").val().replace("\n", "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
});
send() submits the message to the server if the return key was pressed and if the message is not blank or only containing line spaces.
The problem: After sending the message, the textarea is not cleared.
On the first page load, the textarea is empty. Once a message was submitted, there is one blank line in the textarea and I don't know how to get rid of it.
The problem is that the Enter keypress is not being suppressed and is doing its usual browser behaviour (i.e. adding a line break). Add return false to the end of your keypress handler to prevent this.
$("#area").keypress(function (e) {
if (e.keyCode != 13) return;
var msg = $("#area").val().replace(/\n/g, "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
return false;
});
Thomas, the e.preventDefault(); would need to be wrapped inside a conditional applying it only to the enter key.
// Restrict ENTER.
if (e.keyCode == '13') { e.preventDefault(); }
The whole function would look something like this (with commenting):
// Key Press Listener Attachment for #area.
$("#area").keypress( function (event) {
// If the key code is not associated with the ENTER key...
if (event.keyCode != 13) {
// ...exit the function.
return false;
} else {
// Otherwise prevent the default event.
event.preventDefault();
// Get the message value, stripping any newline characters.
var msg = $("#area").val().replace("\n", "");
// If the message is not blank now...
if (!util.isBlank(msg)) {
// ...send the message.
send(msg);
// Clear the text area.
$("#area").val("");
}
}
} );
You'll want to use the event.preventDefault() function to prevent the default event action from happening, in this case adding the enter character:
$("#area").keypress(function (e) {
e.preventDefault();
if (e.keyCode != 13) return;
var msg = $("#area").val().replace("\n", "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
});
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 have some code like this:
$(document).keypress(function(e){
if(e.shiftKey && e.keyCode == 13){
console.log(e)
executeScript();
//$document.createElement("#textarea");
//if (error) {
// return false;
//} if (correctly executed) {
// create new box
// return true;
//}
return false;
}
})
The line $document.createElement("#textarea"); only expands a line, but I want to create another textarea when the user submits with shift+enter.
Also, to prohibit the user submitting multiple times and creating multiple unused textareas, could I focus on just the active textarea (where the cursor is)?
Here is a fiddle
You can get the ID of the the element from the event as:
event.target.id
And it is easier to use Jquery to create a new text area.
$(document).keypress(function(e){
if(e.shiftKey && e.keyCode == 13){
alert(e.target.id)
//executeScript();
var textArea = $('<textarea rows="2" cols="20" id="four"></textarea>');
$("#contnr").append(textArea);
//$document.createElement("#textarea");
//if (error) {
// return false;
//} if (correctly executed) {
// create new box
// return true;
//}
return false;
}
})
I hope it helps =]
var btn = document.createElement("textarea");
document.body.appendChild(btn);
I have a textarea, and on each enter i want it to get blank if something has written. but my problem is; on the first enter it line breaks, and you continue to write from the second line. it only happens at the first enter. there is no problem with emptying the textarea, you just continue to write from the second line, which is the problem.
onkeydown= if(event.keyCode == 13){
sendMessage();
}
function sendMessage(user){
var message = $('#textarea').val();
$('#textarea').val('');
}
if(event.keyCode == 13) {
sendMessage();
if (event.preventDefault) event.preventDefault();
return false;
}
keydown happens before the character is entered in the textarea, so you just have to call preventDefault on the event so it doesn't enter a line break after you've called your function that clears the text-area. return false alone should be enough too if the code above is inline in the HTML, which isn't really recommended. See updated solution below:
For unobtrusiveness and back-compat, I'd recommend doing it all with jQuery:
$('#textarea_ID').keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
var message = $(this).val();
$(this).val('');
//rest of your function using `message` here
}
});
Fiddle
In jQuery use the which property for the code. Then return false with e.preventDefault();
var field = $('.classname');
field.keydown(function(e){
if(e.which==13){
sendMessage();
e.preventDefault();
}
});
Simply add return false; to your keydown function. This prevents the default action of the key (a newline in this case) from being executed.
You may also want to include code to handle Internet Explorer's way of getting keycodes. Your new function would be:
onkeydown = function (e) {
// Gets keycode cross browser
e = window.event ? window.event : e;
var keycode = e.keyCode !== null ? e.keyCode : e.charCode;
// Checks if it was the enter key that was pressed (enter = keycode 13)
if (keycode === 13) {
// Calls function to do stuff
sendMessage();
// Cancels the default action of the (enter) key
return false;
}
}
I want to submit the form by press the ENTER key.
But it also change the line in content.
How to prevent this?
This is my code, but when hit ENTER, the ... run and Cursor moved to the next line:
function postmessage(e) {
if(e) {
e.preventDefault = null || e.preventDefault;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
....
return false;
}
function submitmessage(e) {
if(e.keyCode == 13) {
postmessage(e);
}
return false;
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
bindEvent(text, 'keydown', submitmessage);
Generally it is a bad idea to screw around with default behavior of the browser. Personally I would hate it if I was typing in some text, hit enter and bam, without a proper review of my data it get's submitted?!
If you don't want people to enter multiple lines in a textarea, why not make it a regular textbox (<input type="text" />)?
While I completely agree with #Peter in that this will create a very awkward and annoying user experience, here's how to achieve it code-wise: Capture the event on a keydown, and bypass the newline with event.preventDefault(). Then manually submit your form.
Something like this:
var el = document.getElementById('#my_textarea');
if (el.addEventListener)
{
el.addEventListener('keydown', checkEnter(event), false);
}
else if (el.attachEvent){
el.attachEvent('keywodn', checkEnter(event));
}
function checkEnter(event)
{
var charCode = (event.which) ? event.which : event.keyCode
// Enter key
if(charCode == 13) {
event.preventDefault();
document.myform.submit();
return false;
}
}
MDN Docs:
https://developer.mozilla.org/en/DOM/event.preventDefault
https://developer.mozilla.org/en/DOM/element.addEventListener
e.stopPropagation(); stopped the default action.
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/