Cancel form submit but allow enter key event - javascript

I'm trying to disable Enter key submit on a form but allow the Enter key event to be registered for some other code I have listening. Is this possible?
$('#createPost :input').on("keypress", function(e) {
if(e.target.id == 'post-author' && e.which == 13){
e.stopPropagation();
e.stopImmediatePropagation();
}
});
Is not working :( it still submits the form

You need to call e.preventDefault() to cancel submit action.
return false; from handler also works. And that works in more ancient browsers, even though this is not important with jQuery.

Related

form submit trigger in html

In HTML, a form can be submitted by
clicking the submit button
pressing enter when the focus is on the submit button
by pressing enter on the input field
Is there a way to find out which of the three methods was used to submit the form?
HTML doesn't have any built-in way of knowing, as far as I know. You'd have to catch the necessary events and keep the state in memory. Something like the following:
Set a bool to true when the input receives focus. Set it back to false when it loses focus.
Set a bool to true when the button receives focus. Set it back to false when it loses focus.
Subscribe to the click event on the button, set a bool to true
Subscribe to the keydown event of the keyboard, check whether it is the enter-key and set a bool to true.
Now you should have the necessary information to know what actions the user took to submit the form. jQuery should be able to help you with all these events.
Also, I believe the form is also submitted when the form has focus (so not just the button or the input) and you press enter. I'm not sure if this is the actual form having focus, or any control inside the form.
So, what you're trying to achieve will require some hacking around. Are you sure you can't provide your users the experience you want in some other way?
I would use the keypress method of jquery to capture if a user is pressing the enter key. Along with the mousedown method to capture the click. The jquery and HTML code would look like this:
HTML:
<form id="myForm">
Name<input type="text" />
Address<input type="text" />
<button id="submitBtn" type="button">Submit</button>
</form>
jQuery Code:
$('#submitBtn').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed "enter" key on the submit button');
}
event.stopPropagation();
});
$('#myForm').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed "enter" key in the input field');
}
event.stopPropagation();
});
$('#submitBtn').mousedown(function(event){
alert('You clicked submit');
event.stopPropagation();
});
JsFiddle
Just apply different function to each action. To prevent the form fires its default action, you have to put return false; or event.preventDeafult(); in the callback function.
see the example: http://jsfiddle.net/6krYM/
HTML:
<form>
<input type='text' id='input'>
<input type='submit' value='submit' id='submit-button'>
</form>
JavaScript:
$("#submit-button").click(function(){
alert("click on submit button");
return false;
});
$("#input").keypress(function(e){
if (e.which == 13){
e.preventDefault();
alert("press enter in text");
}
});
$("#submit-button").keypress(function(e){
if (e.which == 13){
alert("press enter on button");
}
return false;
});

prevent default on enter keypress in IE7

I'm solving the problem with default submit button in IE7. When I press "enter" key in input field, than some button on the page is clicked. So I've found the solution for this:
$(document).bind("keypress", function(ev) {
ev.keyCode == 13 && ev.preventDefault();
});
But there is the problem with this code: textarea tag don't get "new line". So I tried this:
$(document).bind("keypress", function(ev) {
if (ev.keyCode == 13 && ev.target.type != "textarea")
ev.preventDefault();
});
It works but looks dirty. The question is: can you advice better solution for the Problem?
Thank you in advance.
If it is to simply prevent the form submission on enter keypress, test on the keypress when the form is trying to submit...
$(your_form).submit(function(ev){
if (ev.keyCode == 13){
// Prevent form submission behaviors if the event was fired by enter keypress
ev.preventDefault();return false;
}
// And code for form submission here, or just keep the return true to make it behave normally.
return true;
});
This is not dirty. But if you want one line, you still could do with:
ev.keyCode == 13 && ev.target.type != "textarea" && ev.preventDefault();
A more elegant solution would be to use jQuery's submit handler and return false:
$('#myForm').submit(function(ev){
// custom form handling code here
return false;// prevent browser default form submission
});
Alternatively, you could also call .preventDefault() on the event object, passed in to the submit handler.

Prevent a button from submitting a form when 'enter' is pressed in a certain location

I have a table with a quick edit function (updates only one field using AJAX), and I wish for 'enter' to submit the change. Trouble is, I have a button on a form on the same page, and every time I press 'enter' the action attached to that button (i.e. submit the form, which I do not want to do) is fired, and I cannot figure out for the life of me how to prevent that.
I've tried the following code, preventing the default on the keyup event (which is probably wrong) and on the button. My understanding though is that you prevent the default of an event, not an object, so I'm really not sure what to do -
/** Capture a key press (while a field within the quick edit row is selected) */
qeRow.keyup(function(e){
e.preventDefault(); // Also tried '$('#change-permissions-button').preventDefault'
if(e.keyCode === 27) { // Cancel on 'escape' (This is working fine)
return inlineEditUserGroup.revert();
} else if(e.keyCode === 13) { // Save the data on 'enter'
return inlineEditUserGroup.save();
}
});
Thanks.
Try listening to the keydown or keypress event.
qeRow.keypress(function(e){
e.preventDefault(); // Also tried '$('#change-permissions-button').preventDefault'
if(e.keyCode === 27) { // Cancel on 'escape' (This is working fine)
return inlineEditUserGroup.revert();
} else if(e.keyCode === 13) { // Save the data on 'enter'
return inlineEditUserGroup.save();
}
});
I guess the keyup-event is triggered 'to late', because it only listens to a key after you pressed in, and than the form is already submitted.

JQuery Event for when user presses enter?

What's the simplest way to have a function called whenever the user hits enter after typing in a textbox?
You'll need to listen for the keypress event. It's probably easiest to do this with delegate:
$(document.body).delegate('input:text', 'keypress', function(e) {
if (e.which === 13) { // if is enter
e.preventDefault(); // don't submit form
// do what you want here
}
});
<textarea id="text"></textarea>
$('#text').keydown(function(e){
if (e.keyCode == 13) {
alert('Enter was pressed.');
}
});
http://jsfiddle.net/dNfC2/
HTML code
<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>
jquery code
$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});
Running example here : http://jsfiddle.net/Xamkp/5/
try this:
jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });
you will need a plugin:
jquery.hotkeys
Well it's rather simple to do in the form you asked:
$('#idOfTextBox').keyup(function(event){
// enter key pressed
if(event.keyCode=='13')yourFunction();
});
Take note this will still append the enter key to the box. You might wanna try keydown or keypressed if you don't want that.
Be sure to check keyUp() for more detail.
Put the <input> in a form, and write a handler for the form's submit event.
This way you're not explicitly looking for any particular key; you're just waiting for the form to be submitted normally. And in every mainstream browser, pressing enter while filling out a form will submit the form.
Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form).

Change Enter from submission to Tab?

Users don't like the fact that the Enter key submits the page. So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.
I have tried many javascript snippets found on the net but none have worked so far. The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.
e.returnValue = false;
e.cancel = true;
Page still submits with the above in the keydown event handler. Same effect with return false in the keydown event handler. The handler is firing, tested by putting a breakpoint in it with firebug.
This needs to work with both IE and Firefox.
Don't say "don't do this".
1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.
2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.
This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:
Here's a simple example:
$("input").bind("keydown", function(event) {
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
$(this).next("input").focus();
}
});
Example: http://jsfiddle.net/andrewwhitaker/Txg65/
Update: If you have elements in between your inputs, using plain next() will not work. Instead, use nextAll():
$("input").bind("keydown", function(event) {
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
$(this).nextAll("input").eq(0).focus();
}
});
http://jsfiddle.net/andrewwhitaker/GRtQY/
$("input").bind("keydown", function(event) {
if (event.which === 13 && this.type !== 'submit') {
event.preventDefault();
$(this).next("input").focus();
}
});
Based on this post:
http://forum.jquery.com/topic/how-to-find-next-node-in-focus-order
I came up with this. I eventually chose not to use focasables though, and instead use input to get the effect I wanted. The .not is to prevent image buttons and submit buttons from being effected, so that they still have the default action of submit on enter whenever they have focus.
$(document).ready(function() {
var focusables = $(":input").not('[type="image"]').not('[type="submit"]');
focusables.keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
}
});
});

Categories