Line break on keydown - javascript

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

Related

phonegap tel softkeyboard done action

i try to bind an event to done action on soft keyboard tell mode.
but i can't catch any event.
i tried use keyup/ keydown, blur and change events.
nothing happened in iPhone and android.
$("input").bind('keyup', function(event){
var key;
if(window.event)
key = window.event.keyCode;
else
key = event.which;
if(key == 13 || key == 10){
alert(key);
}
});
$("input").bind('blur', function(event){
alert("blur");
});
$("input").bind('change', function(event){
alert("change");
});
Any solution?
You are missing a close } after the one if.
Also, maybe the selector you are using $('input') is too broad try something specific, i use somelike like this:
$('#element_id').live('keypress',function(e){
console.log('keypress: '+e.keyCode);
if (e.keyCode != 13) {
console.log('is not an enter key');
}
else {
console.log('is an enter key going to submit');
Fling.poo();
return false;
}
});

How make input not rebind the page?

I have a input on page in some div:
<input style='border:1px solid black;' type='text' id='inputFindBy_Name' />
and o jquery javascript function monitored it:
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
var searchField = "Name";
var searchValue = $(this)[0].value;
var pageIndex = "1";
var sortField = "Name";
Application.Services.ProductTypeService.LoadMainGridProductType(pageIndex, sort, sortField, searchField, searchValue, ResultLoadMainGridProductType, ErrorLoadMainGridProductType);
}
});
when user typed something and pressed ENTER (event.keyCode == 13) I need do some thing but without reloading the page. How do that?
Try this one
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
// needed do something here without reloading the page
return false;
}
});
just like a link.
Just return false from within the function:
var code = event.keyCode || event.which;
if (code == 13) {
// do what you have to do.....
return false;
}
Edit: the keyup event is triggered "too late" after the form submission event was already dispatched - you can't cancel or stop it in that stage. So, handle the keypress event instead. Change the line to:
$("div[id=mainGridPage] input").bind("keypress", function (event) {
And the return false; will indeed stop the form from submitting.
Live test case.
You need to do a event.stopPropagation() and maybe the return false;. Please use event.which because event.keyCode is not compatible with all browsers, also you are using div[id=mainGridPage] input which searches for an ID, a better way to put this down is: div#mainGridPage input, and probably faster.
$("div#mainGridPage input").bind("keyup", function (event) {
if (event.which == 13) {
event.stopPropagation();
// needed do something here without reloading the page
return false.
}
});
try this. this will work i think:
$("div[id=mainGridPage] input").keypress(function(event) {
if (event.keyCode == 13) {
// do your code
console.log('hello');
return false;
}
});

How to prevent ENTER key to change line in web form

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.

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/

Remove line break from textarea

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("");
}
});

Categories

Resources