Prevent textarea with only <br> from submitting - javascript

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

Related

Textarea enter keypress not working because of form submit enter prevention

I have a form in which I've used the following code to prevent the form being submitted on the press of 'Enter'.
<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
</script>
As a result, the 'Enter' key is not working in any textarea input. I can't enter a new line because of the body function. How do I solve this?
<textarea name='description' placeholder="Any other information (optional)"</textarea>
I have find solution.
You prevent enter key on all the form element. Just add some tweak to your code and its done. Just skip prevention of enter key when your focus is on textarea. See below code :
$(document).ready(function() {
$(window).keydown(function(event){
if(event.target.tagName != 'TEXTAREA') {
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
}
});
});
To prevent the form from submitting, try this instead:
$("form").submit(function(e){
e.preventDefault();
}

How to prevent enter key from submitting a form but still allow enter to work? [duplicate]

This question already has answers here:
Prevent users from submitting a form by hitting Enter
(36 answers)
Closed 6 years ago.
I'm using XOXCO Tags-Input.
Here is a demo http://xoxco.com/projects/code/tagsinput/example.html
So in order to complete a tag i have to hit enter but when i hit enter it submits my form.
I can disable enter for the whole form with this code but then i can't complete a tag.
$("#form").keypress(function(e) {
//Enter key
if (e.which == 13) {
return false;
}
});
So i still need enter to work but i also need it to not submit the form and i'm not sure how to do that.
You need to prevent the default behavior of the enter press, which is to submit the form. For example...
$('#form').keypress(function(e){
e.preventDefault(); // prevent form submission
// do stuff with the keypress
$('#form').submit(); // now, submit the form
});
The first thing that comes to mind is:
$('form').on('keypress keydown keyup', function(e) {
if (e.which == 13) {
//alert(e.which);
e.preventDefault();
return false;
}
});
https://jsfiddle.net/Lhujkub7/
Ok, i solved it in case anyone else runs into this problem here is what i did.
$('form input').keydown(function (e) {
if (e.keyCode == 13) {
var inputs = $(this).parents("form").eq(0).find(":input");
if (inputs[inputs.index(this) + 1] != null) {
inputs[inputs.index(this) + 1].focus();
}
e.preventDefault();
return false;
}
});

How to prevent form submission using the keyboard (esp. the space key)

I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.
I have written this code:
$('button').keydown(function (e) {
if (e.which === 10 || e.which === 13 || e.which === 32) {
return false;
}
});
However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?
Edit:
Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.
Edit 2:
I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.
Just found out: handling space (32) on keyup will prevent the click event.
Updated fiddle: http://jsfiddle.net/3JmtY/2/
Missed the Point of your Question. After some googleing if found the following trick:
Bind the keypress event to your from and listen to it's keycode. If the keycode is 13
(enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).
Her is a fiddler code example:
HTML:
<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>
JavaScript:
$('#target').keypress(function (event) {
var code = event.keyCode || event.which;
if (code == 13) {
event.preventDefault();
return false;
}
});
$('#target').submit(function (event, data2) {
debugger;
alert('test');
return false;
});
Fiddler: http://jsfiddle.net/ggTDs/
Note that the form is not submited when enter is clicked!
Use below code. 13 for Enter key and 32 for Spacebar.
$("#form_id").on('keydown keyup keypress', function( e ) {
if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
e.preventDefault();
return false;
}
});

Submit value on pressing Enter in textarea and pressing Shift+Enter should go to next line

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

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

Categories

Resources