The title speaks for itself... I have a couple of forms, one of them is just a single text input form and the other one is composed by two text inputs. I do not want any submit button in any of them, I want each form to submit whenever the user presses the ENTER button at any text input:
The form composed by just one input submits everytime the user presses the ENTER button - Perfect!
The second form composed by two text inputs does not behave this way, it does not submit when the user presses the ENTER button at any of both inputs.
Is there a way to make a form with more than one text input behave this way and avoid having a submit button in it?
Try adding this between the <form></form> tags
<input type="submit" style="display: none" />
Tested it and it works on Firefox and Chrome. If you have a submit input type in the form, enter should automatically submit it, regardless of whether it's visible or not.
I am actually using this myself in a login form, though in the username field, it makes more sense to move to the next field than to submit. Just in case you have a similar use case, here's the code I used (requires jQuery)
$('#username').keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
$('#password').focus();
event.preventDefault();
}
});
Note that there is a slight bug though -- if the user selects a browser autocomplete username and presses enter, it still moves to the next field instead of selecting it. Didn't have time to debug this, but if someone can figure out how to fix it, that would be cool.
I was looking for a solution to this problem and want to share my solution, based on many posts over here. (Tested on modern Chrome/Firefox/IE)
So, using only Javascript the follow code submits the form if ENTER key is pressed on any field or if the button Submit is pressed. After that it clear/reset the form, which is a nice thing to do.
Hope it helps.
<!DOCTYPE html>
<html>
<body>
<p>Based on http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit</p>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<div onKeyPress="return myFunction(event)">
<form id="form01" action="demo_form.asp" onsubmit="return false;" >
Enter name: <input type="text" name="fname">
<input type="button" value="Submit" onclick="myFunction(0)">
</form>
</div>
<script>
function myFunction(e) {
if((e && e.keyCode == 13) || e == 0) {
alert("The form was submitted");
document.forms.form01.submit();
document.forms.form01.fname.value = ""; // could be form01.reset as well
}
}
</script>
</body>
</html>
Be sure that your inputs are inside "form" element and give the "form" element an "action" attribute.
You will have to look for the Enter key press. This post here shows how to do that.
Enter key press event in JavaScript
You can use the code below to submit a form after pressing Enter.
<input id="videoid" placeholder="Enter the video ID">
<button id="mybutton" type="button" onclick="myFunction()">Submit</button>
<script>
var input = document.getElementById("videoid");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("mybutton").click();
}
});
</script>
Related
I have folowing form:
<form method="post">
<input type="submit" name="submit" value="Save" class="button">
<input type="text" name="search_input" id="search_input">
<input type="submit" name="submit" value="Search" id="searchBtn" class="button">
</form>
Desired behavior is that when I enter some text to input field and hit Enter key, form shall post submit/Search and search_input.
Instead I get two separate posts:
request.form['submit'] =
ImmutableMultiDict([('submit', 'Save'), ('search_input', 'exampletext')])
ImmutableMultiDict([('search_input', 'exampletext'), ('submit', 'Search')])
I also tried to use following js, but the result is same:
var input = document.getElementById("search");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchBtn").click();
}
});
Do you have any idea, what's wrong and how to fix it?
From your js script i understand that you want the form to only click search and not save when you press the enter key?
If that is so then you need to change the name of the two buttons because form submit uses the name attribute to identify elements.
Since both your inputs have the same name you get two posts.
Edit: I just found out that the first submit in the form is clicked by default when you press the enter key (Without needing any js code), So in your case when you press the enter key the first button (Save) is pressed by default and from your js script the second button (Search) is pressed.
So you just have to put the search button on top of the save button and use CSS to change the order in the webpage
UPDATE 10/9/15
My original question is below and is unclear and does not fully describe my problem because it focuses on the keyup event listener when its actually the double submission of the form (once from the change event and once from the implicit submission both triggered by keypress of the enter key) as the root problem... I have reviewed the code some more and here is an example demonstrating my true problem:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<form method="GET" action="#">
<input type="text" />
<input type="submit" />
</form>
<script>
$('form>input[type="text"]')
// Change event triggered by both enter key and tab key
.on('change', function (e) {
e.preventDefault();
console.log('change event');
$('form').submit(); //This emulates a more complex ajax request
});
$('form').submit(function (e) {
// You will notice the console logs this twice if you hit enter instead of tab.
console.log("form submitted");
});
</script>
</body>
</html>
If you enter something into the input box and hit the enter key then you will see in the console that the form submits twice, once from the change event and once from the implicit submission of the browser.
I want to stop the form submitting twice (you will notice I have already tried preventDefault in my code above). The answer appears to be to preventDefault specifically on the keypress (not keyup) of the enter key (many thanks to #JotaBe)
ORIGINAL QUESTION
So I have an event listener for the enter key on an input something like so
$(element)
.on('keyup', function (e) {
if (e.which === 13) {
event.trigger();
}
}); `
Specifically the code is from this plugin
This is interfering with the implied submission which is standard on most browsers, as per the W3 standard, and causing the form to submit twice.
What I would like to know, does the implicit submission happen before or after the explicit submission of my form with the event listener?
And for bonus points which version (or where can I find out which version) did 'implicit submission' get added to various browsers? (so I know how far back my code will be compatible)
Second question first
The implicit submission, although not with that name, exists at least from something as old as HTML 2 specs of novemeber 1995. Last lines of section 8.2:
When there is only one single-line text input field in a form, the user
agent should accept Enter in that field as a request to submit the form.
So, as we say in Spain, is as old as coughing.
And then, the main stuff
When you handle an event, unless you cancel the default action, when the code in your handler finishes running, the default action is executed.
Your code is triggering the event, and not cancelling the defautl action. That's why the submission happens twice, once for the handled event, and once for the additional triggered event.
In the case of jquery you've got to call event.preventDefault() to avoid the default action to execute.
Please look at this fiddle to check 2 things:
1) By default, when you press enter on a form, the form is submitted To be more precise, it must simulate a click on the first submit button of the form. Thus, if this button is disabled, or doesn't exist, nothing happens.
2) If you want to prevent the default behavior, you must handle the keypress (not keydown or keyup) event on the textbox, and invoke the event's preventDefault method.
3) According to the specs, this should only happen when there is a single textbox (of type text, number, date, url,email, etc.). But it doesn't work like this in most browsers, for example in desktop versions of Chrome 45, IE 10 and FF27 & FF33. I didn't test other versions.
Fiddle code:
// This suppres the default behavior of submitting the
// form when the enter key is pressed in the textbox
$('#form2').on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
console.log('key press 13');
}
});
// This event is triggered when any form is submitted
// (in fact, the submission is prevented).
$('form').on('submit', function(e) {
console.log('Sending form', e.target.name);
e.preventDefault();
});
with this HTML:
<div>
<p>Form 1, default enter behavior, when there is only a textbox, and there is a submit button</p>
<p>If you press enter, it's submitted</p>
<form method="GET" id="form1">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 2: prevents default behavior on textbox</p>
<p>If you press enter the form is not submitted</p>
<form method="GET" id="form2">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 3: submit shuld only happen if there is only one textbox, but it depends on the browser</p>
<p>If you press enter the form should not be submitted, because there are several textboxes, but I bet it will be submitted</p>
<form method="GET" id="form3">
<input type="text" />
<input type="text" />
<input type="submit" />
</form>
</div>
add global variable like
var submited = true;
validate like
$(element)
.on('keyup', function (e) {
if (submited) {
submited = false ;
event.trigger();
}
});
I'm trying to set the submit button in an ASP.NET website to another submit button when clicking enter key on the keyboard. I've so far accomplished to do so, but problem is it still sends the second submit button too. I tried returning false in the onkeypress event in the input elements, but then it won't let me write anything to the text input boxes..
This is my javascript function:
function button_click() {
if (window.event.keyCode == 13) {
document.getElementById("msSend").focus();
document.getElementById("msSend").click();
}
}
And a sample text input box:
<input type="text" id="msname" name="msname" runat="server" onkeypress="button_click()" /></td>
Any suggestions?
I fixed it! I had some buttons in my MasterPage that was for some reason defined as type="submit".
I changed:
<button name="bmenu" onclick="DisableHL('bmenu'); location.href='<%= movies %>'; return false;" class="btn">סרטים</button>
to:
<button name="bmenu" onclick="DisableHL('bmenu'); location.href='<%= movies %>'; return false;" class="btn" type="button">סרטים</button>
And there it fixed it! ;)
I have a form where I am taking two parameters from user and submitting form on press of Go button as well as on press of Enter key.
But in textbox when user types one char , textbox shows results for auto-complete.
And if user uses arrow keys to navigate through options and presses enter on a particular auto complete result, for gets submitted before selection of that selected option.
I want that user should be able to go down using arrow key, hit enter when he gets his option among the autocomplete list shown. and then if he presses enter , the form should be submitted
Here is the code in jsp
<tr> <td>param1: <input type="text" id="param1" placeholder="PARAM(Required)" onKeydown="Javascript: if (event.keyCode==13) getData();"></td>
<td>Merchant ID: <input type="text" id="merchant" placeholder="Merchant ID(Optional)" onKeydown="Javascript: if (event.keyCode==13) getData();"></td>
<td><button class="btn" onclick="getData()" style="position:relative;">Go</button>
</td></tr></thead></table>
on press of enter key I am calling getdata function in JS which calls the servlet
How can I go about this?
Thanks
If you can, please share with us more information about the code that you are using, the plugin or framework, etc...
So far with the poor information you share, you can disable the form submission if the enter hit is focussed on the input where the autocomplete goes. This is an example with jQuery
HTML
<input type="text" id="myInput" />
Javascript
$(function() {
$("#myInput").keypress(function(e) {
var KeyCode = (e.keyCode ? e.keyCode : e.which);
if(code == 13) return false; // 13 is the code for enter
});
});
You can read more examples about event handling here: http://api.jquery.com/category/events/
I want to prevent the enter key from submitting the form, I want it to act as a TAB key to just jump to the next field in the form or the next element.
Is this possible in HTML/JS?
if not possible to make the enter button act as a tab, is there a way to prevent the submission of the form and make only the form be submitted using the buttons on the HTML??
EDIT:
I have received a solution to this problem when I was asking for another problem!
here you can find the solution.
For accessibility/usability reasons, you really shouldn't prevent the Enter key from submitting the form (assuming the browser was going to do that anyway; IIRC, some older browsers didn't).
Assuming that you want to do this because the submit button has a click handler you'd like to happen for every form submission, you should instead move that code into a separate function and invoke it from a the form's submit event.
In jQuery, it would look something like:
$('#myForm').submit(function(e) {
if (!isValid()) {
e.preventDefault(); // Could also be `return false;` but I prefer preventDefault.
}
});
See the docs.
FYI, if you're trying to do some validation, you should check out the validation plugin.
<html>
<body>
<script>
function tmpFn(val){
if(event.keyCode=='13'){
if (val<4)
document.forms["yourform"].elements["box" + (val+1)].focus();
else
document.yourform.submit();
return false;
}
return true;
}
</script>
<body>
<form name="yourform" action="#">
<input type="text" name="box1" onkeypress="return tmpFn(1)"><br>
<input type="text" name="box2" onkeypress="return tmpFn(2)"><br>
<input type="text" name="box3" onkeypress="return tmpFn(3)"><br>
<input type="text" name="box4" onkeypress="return tmpFn(4)"><br>
<input type="submit" name="done" value="Submit">
</form>
</body>
</html>
EDIT: Refrain from using 'eval'.. Thanks Tim and Andy!
It might be possible to solve this using some jQuery - although I don't know how to imitate a keypress.
$(document).keyup(function(e) {
if(e.keyCode == 13)
{
//Code to imitate keypress of Tab key
}
});
Edit: Made a quick jsFiddle to "imitate" tab presses, which would go to the next field like you mentioned. (This one works based on the Enter key being pressed in a field)
jsFiddle
Off the top of my head, to prevent the enter button from submitting the form, don't use a submit button, rather use a <input type="button" ... onclick="submitForm();"> to call javascript to submit the form. I could be wrong, but I believe this should prevent pressing enter on any other element submitting the form.