HTML textarea linebreak on enter key press don't work - javascript

I have a textarea and when click enter it doesn't insert a linebreak,
I tried to use the following code, But, when i press enter, it goes to the end fo text and add new line.
$("#descre").on('keydown', function(e) {
var code = e.keyCode || e.which;
if (code == 13) { //Enter keycode
event.preventDefault();
var s = $(this).val();
$(this).val(s + "\n");
}
});
I want to make a normal enter press, like ex: jsfiddle

My textarea was not working well, so to accept enter key press on normal behaviour i used the code:
$('#descre').keypress(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
this.value = this.value.substring(0, this.selectionStart) + "" + "\n" + this.value.substring(this.selectionEnd, this.value.length);
}
});

You have passed e in the function as argument but in the if block you are doing event.preventDefault() change it to e.preventDefault()
//i try this one
$("#descre").on('keydown', function(e) {
var code = e.keyCode || e.which;
if(code == 13) { //Enter keycode
e.preventDefault();
var s = $(this).val();
$(this).val(s);
}
});
You are adding an extra line in the end yourself. Thats why it is inserting the extra k=line

Related

break string into pieces and wrap each piece in html with js

I'm using a content editable div to try and make tags. When the user presses return, I need to be able to select the previous text (but not the previous tags) and turn it into a new tag. A tag will be wrapped in , so an example would be:
<em>tag1></em><em>tag2</em>tag3--- // about to press enter for tag3
This is what I'm thinking so far:
$('#tags').keydown(function(e) {
if (e.keyCode == 13 || e.which == 13) {
paste('---'); // this adds a separator when the user presses enter
var content = $(this).html();
var newTag = // the text between the last </em> and ---
newtag.wrapInEm(somehow);
event.preventDefault();
return false;
}
});
Maybe you should separate the current tags from the new tag creation.
HTML
<div id='tags'>
<span id='tag-list'></span>
<span id='tag-new' contenteditable></span>
</div>
JS
(function($){
var tags = ['tag1', 'tag2'];
$('#tag-new').on("keydown", function(e) {
e.preventDefault();
if (e.keyCode == 13 || e.which == 13) {
// if (!saveToDB) return;
tags.push($(this).text());
_renderTags();
return false;
}
});
$('#tag-list').on("click", "em", function(e){
// if (!deleteFromDB) return;
var idx = tags.indexOf($(this).html());
tags.splice(idx,1);
_renderTags();
});
function _renderTags(){
$('#tag-list').html("<em>" + tags.join("</em><em>") + "</em>");
}
$(document).ready(function(){
// loadTagsFromDB
_renderTags();
});
})(jQuery);
It's hard for me to understand your question--there are a handful of typos and your html sample doesn't make any sense.
Nevertheless:
How about using the [.wrap(]http://api.jquery.com/wrap/) jquery function?
$('#tags'.keydown(function(e) {
if (e.keyCode == 13 || e.which == 13) {
$([selector for previous text]).text().wrap(<em></em>);
}
});

One line only for contenteditable element

I try to make a element via using contenteditable to submit some title, That way I want users type/paste title only one line.
$('.title').on('keypress',function(e) {
var code = e.keyCode || e.which;
if(code == 13) {
e.preventDefault();
}
}).on('paste',function(){
var text = $(this).text();
$(this).html(text).focus();
});
Problem is paste event, When I paste some text, I can't use .focus() to select/point text to the last charecter.
What I did wrong ?
I have idea now...
jQuery :
$('.title').on('keypress',function(e) {
var code = e.keyCode || e.which;
if(code == 13) {
e.preventDefault();
}
}).on('paste',function(){
$('br,p',this).replaceWith(' ');
});
CSS : (not request)
.title br {display:none;}

Line break on keydown

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;
}
}

How to disable Enter/Return Key After a function is executed because of it?

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/

jquery ctrl+enter as enter in text area

I am trying to reproduce standard instant messenger behavior on TEXT area control:
enter works as send button. ctrl+enter as real enter.
$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e)
{
if (!e.ctrlKey && e.keyCode == 13)
{
SendMessage();
return false;
}
else if(e.keyCode == 13)
{
$(this).val($(this).val() + "\n");
}
return true;
}
I have tried with both commented line and without. Not works. simple enter works as expected.
Any ideas how to add enter on ctrl+enter?
key code is not problem. they are detected correctly. so all if's works as expected. But appending new line works incorrectly (in FF, Chrome works correctly). So I need correct multibrowser way to insert new line symbol to textarea. If without adding string manually (by some event based on ctrl+enter) it will be better.
changing on keypress event has no effect. "\r\n" not helped.
test page located here
The following will work in all the major browsers, including IE. It will behave exactly as though the enter key had been pressed when you press ctrl-enter:
function MessageTextOnKeyEnter(e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
var val = this.value;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
var start = this.selectionStart;
this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
this.focus();
var range = document.selection.createRange();
range.text = "\r\n";
range.collapse(false);
range.select();
}
}
return false;
}
}
wow what a pain in the ass. i've been playing with this for a while and i have to assume this is just IE being uncooperative. anyway, this is the best i could do this morning and it's super hacky, but maybe you can gain something from it.
explanation: i'm testing with ie8, a textarea element, and courier new. results may vary. ascii character 173 (0xAD) does not display a character, although it counts as a character when moving your cursor around. appending this char after you force a newline gets ie to move the cursor down. before the call to SendMessage we replace the extra char with nothing.
function MessageTextOnKeyEnter(e)
{
var dummy = "\xAD";
if (!e.ctrlKey && e.keyCode == 13)
{
var regex = new RegExp(dummy,"g");
var newval = $(this).val().replace(regex, '');
$(this).val(newval);
SendMessage();
return false;
}
else if(e.keyCode == 13)
{
$(this).val($(this).val() + "\n" + dummy);
}
return true;
}
if you try to do the replacement on every keystroke it's not going to work very well. you might be able to deal with this by white/blacklisting keys and find a method to put the cursor back in the text where it's supposed to go.
A few potential causes:
Define the function before you reference it.
Make sure you're binding the event in the document.ready event, so that the dom item exists when you reference it.
Change else (e.keyCode == 13) to else if (e.keyCode == 13).
Make sure this is a textarea, not an input[type=text].
Consider using keypress instead of keydown.
Some browsers will send keyCode == 10 instead of keyCode == 13 when using the ctrl modifier key (some browsers will send it even when you aren't using the ctrl modifier key).
My answer leads from Ian Henry's answer about keyCode == 10, which seems to be the case in IE (tested in 8 & 9). Check if you are dealing with a windows event and ket the key code.
$('#formID #textareaID').keypress(function(e) {
if(window.event) {
var keyCode = window.event.keyCode;
}
else {
var keyCode = e.keyCode || e.which;
}
if( (!e.ctrlKey && (keyCode == 13)) ) {
//do stuff and submit form
}
else if( (e.ctrlKey && (keyCode == 13)) || (keyCode == 10) ) {
//do stuff and add new line to content
}
});
You can check for the ctrl and alt as in
$(document).ready(function() {
$('#myinput').keydown(function(e) {
var keysare = 'key code is: ' + e.which + ' ' + (e.ctrlKey ? 'Ctrl' : '') + ' ' + (e.shiftKey ? 'Shift' : '') + ' ' + (e.altKey ? 'Alt' : '');
//alert(keysare);
$('#mycurrentkey').text(keysare);
return false;
});
});
See a working example here: http://jsfiddle.net/VcyAH/
If you can stick with Shift+Enter instead of Ctrl+Enter then the solution is trivial. You don't need any special code as Shift+Enter triggers a line break automatically. Just catch plain Enter to do the sending.

Categories

Resources