Send form when hitting enter - javascript

I have a form in a jQuery enabled site. The form does not feature an <input type="submit"> button. For that reason, it's not submitted when you hit enter. What's the recommended way to emulate such behaviour?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function(){
$("form input:first").focus();
});
//--></script>
</head>
<body>
<form action="" method="post">
<input type="text" name="user">
<input type="password" name="pass">
</form>
</body>
</html>
Update
I'm just trying to add a quick simple improvement to an existing form. I fully understand all the concerns about accessibility but the app itself needs JavaScript and will not run at all without it. A fallback to submit the form would be of little use.

Put a submit button in the form, and make it invisible using JavaScript. This fulfils 2 purposes:
The enter button will work because there is a submit button present
Non-javascript users will be able to use your form

I would capture the keypress event of the input elements, watch for a keycode of 13 (enter) and call submit. Like so:
$("form input").keypress(function(ev){
if (ev.keyCode == 13) {
$("form")[0].submit();
}
});
This code is untested.

Why not just feature a button that is hidden using CSS, or even better JS: in that case the form will remain accessible to people that have JS disabled, and you should get your enter automatically

Use the jquery form plugin.
http://malsup.com/jquery/form/

Recommended? I'm not sure it's recommended to emulate this behaviour at all!
Whilst you can mess around with trying to detect keypress for Enter, there are some subtle browser differences about how Enter presses are supposed to work which won't be quite the same as what you produce. And your form will fail to work at all without JavaScript, which isn't ideal.
So put a submit button in. If you're really adamant that the button shouldn't appear on-page (and I'm not sure that's a good idea), you can always absolute-position it off the left-hand side of the page where no-one can see it.
Note that WebKit will submit the form anyway despite the lack of button. If you must patch this up with messy script, make sure you cancel the default action for the keypress or you may get double-submission.

Safari, Firefox, Opera, and IE8 all do submit the form when you hit enter in text input field. Neither is submit button nor javascript needed. Try yourself.
(Didn't test IE6/7 but I'm 95% sure they do too.)
I agree with other that capturing the enter is not good idea.
Update: the above is true, except that Firefox does not submit a form containing password field and having no submit button. No idea why, can anyone see a reason behind that?
Update 2: ... and except for IE, if there's only one input field.

I used following thing for the same purpose but not for jquery try this may help you.
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.onsubmit();
return false;
}
else
return true;
}

Related

jquery click not getting triggered on IE

I've seen a lot of posts on this issue but none of the solutions worked. The following..
<script type="text/javascript">
$(document).ready(function() {
$("a.login_linkedinbutton").click(function(){
$("#signup-form").submit();
return false;
});
});
</script>
is what I have in the body tag of a page. Also in the body is the form, the html of which in IE shows up like this..
<form accept-charset="UTF-8" action="/auth/linkedin" class="well form-inline" id="signup-form" method="post">
<a class="login_linkedinbutton" href="#">Login using Linkedin</a>
</form>
in IE8, when the link within the form is clicked, the jquery is not getting triggered. It's working in Chrome and Firefox. I've tried:
1) Using the live event to bind the click action
2) Moved the jquery out of the page and into rails assets
Any ideas what else to try?
Use <input type="submit" value="Login using Linkedin">
Why create problems by using a non-standard element and then trying to recover from it?
If you want it to LOOK like a link, just style the button. But why do it? It's poor user experience to suggest the user to go to another page while they're submitting a form. Most users avoid clicking links when they have a form filled because they're afraid of loosing what they just typed.
If you insist using the link, you could try this:
var onLinkedInLogin = function(e){
e.preventDefault(); // stops the link processing
$("#signup-form").submit();
// add return false; if you want to stop event propagation also
// equivalent to calling both, e.preventDefault() and e.stopPropagation().
};
$(document).on('click', 'a.login_linkedinbutton', onLinkedInLogin);
The reason I'm suggesting using .on() instead on .click() is that I guess that on IE, the a.login_linkedinbutton is not present in the DOM when you call the .click().

submit form on 'enter' in IE "web browser"

having a problem with the number one browser for downloading another browser...IE
IE8 fails to submit when you hit enter in a form. here is what i use:
function submitOnEnter() {
if (browserName=="Microsoft Internet Explorer")
{
var key;
if (window.event){
key = window.event.keyCode; //IE
}
if(key == 13){
document.forms['myform'].submit();
}
}
}
and this is located on the text input :
onkeyup="submitOnEnter()"
The form seems to submit when i press enter twice?? but not once.
Can you help?
Okay guys, i fixed it using....
<!-- Fix for IE bug (One text input and submit, disables submit on pressing "Enter") -->
<div style="display:none">
<input type="text" name="hiddenText"/>
</div>
Weird eh? Maybe this will work for some of you and not others. some solutions didnt work for me, this one did.
Submit works when pressing ENTER when there is a submit button present in the form <input type="submit">. You can hide the button if you want. No need to intercept keystrokes.
My problem was that i checked for the submit button. But IE seems not to send the submits in the $_POST array. Adding a hidden field solved my problem.

Form submission on pressing enter button

I am handling ajax suggestions using keyboard and mouse, it is capturing every keyevent except enter key(13). What I want is to get the "selected suggestion value" into the text box. For this I am handling keyevent = 13. Now the problem is when I am pressing enter key, my form get submitted instead of going into the "if block" where I am checking (keyevent = 13).
I am using struts <html:submit> tag to submit my form. I guess, the browser automatically set the focus into first <html:submit> tag that comes in its place. How to defocus this? I tried setting focus at other fields but trick doesn't work.
The other way is, I can use simple <html:button> and can get the things working, but the system already using <html:submit>. So, getting approval and modification is quite hectic.
Code for submit button:
<html:submit styleClass="btn" property="method.saveVisaRequestForRMG" onclick="bCancel=false" styleId="submitBtn">
and code for event handling:
// Handle ENTER key
case 13: handleSelectedItem(obj, container, cur);
ev.cancelBubble = true;
break;
How to come out of this problem? Please suggest me.
If you use jquery there is a simple way to handle enter press events:
$(window).keypress(function(e) {
if(e.keyCode == 13) {
e.preventDefault();
alert('Enter!');
}
});
After you prevented the default event you can do whatever you want for example posting the data into the server, saying hello or whatever :)
Try to return false; to cancel the event handling of the submit?
Do you have something like:
onsubmit="return formValidator()"

how to remove the default focus on submit button in HTML form?

I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}

How to make an INPUT TYPE="IMAGE" not submit on Enter in WebKit?

In a C#/ASP.NET application, I have a form that renders much like the following (plus a lot more, but this is what matters):
<form method="post" action="">
<input type="image" name="ctl15" src="cancel.gif" style="border-width:0px;" />
<!-- Server side, the above input is a System.Web.UI.WebControls.ImageButton. -->
...more extra fluff...
<input type="submit" name="Button1" value="Proceed" id="Button1" class="button"
style="width:59px;" />
</form>
This form works just fine in Internet Explorer and Firefox, but fails in WebKit-based browsers (Safari and Chrome). The problem is that when the user presses Enter when in an input field, rather than using the mouse to click on the submit button, the image input is activated (which in this case corresponds to a cancel event, exactly the opposite of the "proceed" action that is natural given the UI in question).
What I want to do is to, on an Enter keypress, activate the <input type="submit"> button instead of the <input type="image">, without breaking submission by clicking the image. How can I do that? Preferably in a cross-browser manner so I don't need yet more special cases in the code.
No jQuery solutions, please, since this application doesn't use it (and introducing a whole new library for such a "simple" thing is going to be a very hard sell) - stock JavaScript is perfectly fine, though. Obviously the best would be if it can be done in just HTML and CSS, but I have my doubts about the feasibility of that.
In essence, this question seems to me to be sort of the exact opposite of HTML: Submitting a form by pressing enter without a submit button.
Unfortunately, since the different parts of the UI are rendered by different classes and kept in separate .aspx files (specifically, the <input type="image"> is in one place, and the <input type="submit"> in quite another), reordering the elements in the generated HTML is not really a feasible solution either.
Pure JavaScript:
<script type="text/javascript">
var SUBMIT_BUTTON_ID = "Button1";
window.onload = function(event) {
var arrInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oCurInput = arrInputs[i];
if (oCurInput.type == "text") {
oCurInput.onkeypress = function(evt) {
if (typeof evt == "undefined" || evt == null)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode == 13) {
document.getElementById(SUBMIT_BUTTON_ID).click();
return false;
}
return true;
}
}
}
}
</script>
Tested on IE8 and Chrome, better test on all browsers you think relevant before using it.
This code will handle all onkeypress events for all textboxes in the document and when ENTER key is pressed it will imitate click of the submit button and cancel further handling of the event to avoid conflicts.

Categories

Resources