Form submission on pressing enter button - javascript

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

Related

How to get a submit button to re-enable once validation has taken place

I have a search form (you can see the form here) that uses some javascript to check that at least one field has been completed before allowing a search to take place.
I'm not great with Javascript so please bear with me. I've managed to get the validation working (with the help of brilliant Stack Overflow users), and get the submit button to be re-enabled once the form has passed validation using the following code:
$(function(){
$('#detailed-search-form').on('submit',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if(oneFilled) {
$(this).unbind('submit').submit()
} else {
overlay();
}
});
});
The trouble is that the first click on the submit button doesn't actually submit the form, it simply enables the button. This the needs another click before the form is submitted.
Hopefully there's a way I can get the form to not only re-enable the button when it's clicked, but also submit the form without the need for a second click?
Any help will be greatly appreciated!
Thanks in advance,
Tom
The submit handler you wrote should basically say "hey, if you didn't provide at least one field, I'll prompt you a nice green overlay, otherwise let's move on with the search" - no need to unbind anything.
$(function(){
$('#detailed-search-form').on('submit',function(e){
if( !checkFields($(this)) ) {
// if the form isn't valid, show overlay
overlay();
return false;
} else {
// else just continue with form action
return true;
}
});
});

know the suggestion is opened

I have a html form with no submit button. I want to submit that form upon hitting ENTER button. I used a simple jquery code to submit the form upon hitting ENTER.
$("form :input").keypress(function(e)
{
if(e.keyCode == 13)
{
$(this).parents('form').submit();
}
});
But there is a problem with this code. When i type in text field and want to select a suggestion (these are the suggestions, suggested by browser based on the history for that field) for that field using "ENTER" key it trigger the submit of the current form. I want to skip this as well.
Is there something like in jquery or javascript
$("form :input").keypress(function(e)
{
if(e.keyCode == 13)
{
if(! $(this).is('suggestOpened')) // i want something like this
{
// submit the form
}
}
});
Thanks in advance.
No, there's no such event. You could play with onchange and onblur events to intercept whether the user is filling a particular field, but anyway without a submit button:
There's no way for the user to figure-out how to submit the form
The same action (enter key press) could lead to two different actions, which breaks UI consistency
IMHO you should definitely place a submit button.

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 block form submission when the enter key or return key is pressed?

I have a form that I use JQuery, I don't think I need to put code in this post, the question is pretty basic.
But I would like to block the form from submitting when people press the Enter Key or the Return Key.
At the same time, I have textareas, where the user will need to be able to press the Enter / Return keys.
A quick and nasty hack but generally more reliable than trying to block keypresses in every field: add:
<input type="submit" onclick="return false;" />
at the top of the form. The first submit in a form acts as a default button for when Enter is pressed in current browsers, so by neutering it you prevent an Enter-submission from occurring.
Then use CSS to hide and/or move the button so it can't be seen.
It isn't always a good idea to block Enter-submissions though; it's the standard way the browser is expected to work and some users really do want it.
set a flag at the document level, submitform = false;
validate submissions against this.
change the flag in the onclick handler of the submit button.
Couldn't you add an onsubmit attribute to the form, then check if it was submitted using the enter key?
You could try this
jQuery(document).ready(function(){
validSubmit = false;
})
jQuery('myForm textarea').keypress(function(e) {
if (e.which == 13) {
validSubmit = true; // if the pressed key is enter, then allow submissions
}
})
jQuery('myForm').submit(function(){
if (!validSubmit) {
return false; //if submitting the form is not allowed, then cancel submission
}
})
This cancels all submissions whatsoever unless the enter/return key is pressed on a textarea. If you are using a button, you need to add a function to that too.
jQuery('form button.validSubmit').click(function(){ //or 'form input[type="submit"]'
validSubmission = true;
})

Detect the cursor location

I have 25 components which includes [textarea, textfile, radio, combo, etc...] and I have written a key event so that when "ENTER" is entered, I call a function which will submit the page.
Now my page is getting submitted when I press enter, even in the textarea which should not be. So is there any way that I can not submit the page if it is pressed in the text area?
This happens only in IE7 and IE8; it works properly in all the other browser.
you could probably detect if any of the textarea, etc is not filled out/emtpy/unset. if all of them are filled out properly, send the form.
Did you attach the "key event" to the whole form? The whole DOM? if you did that's a normal behavior.
If you want the "Enter key" to submit the page when the focus is on the submit button then apply this functionality in the onsubmit event - there of course you can perform all the validation you need.
If you just want to exclude the enter key event from the text area - perform a simple check if the the focus is in the textarea that momemnt.
The default behaviour of a form is to submit if the user hits enter inside the form unless the focus is on a textarea, so what you want is the default behaviour. Remove whatever code you have that currently handles keypresses for the form and you'll have what you want.
I'm not sure if this will suit your needs, but you can disable the enter key inside the textarea with something like this:
$(document).ready(function(){
$('textarea').keypress(function(e){
var key = (window.event) ? e.keyCode : e.which;
if ( key == 13 ) {
return false;
} else {
return true;
}
})
})

Categories

Resources