I have a <form> element surrounding several inputs:
<form>
<div class="tr" id="widget306">
<div class="td col-grab">
<button type="button" class="button grab formwidget" id="widget611">m</button>
</div>
<div class="td col-name">
<input type="text" name="name" value="target volume profile 1" id="widget607" class="formwidget textbox">
</div>
<!-- ... etc ... -->
</div>
</form>
I would like to trigger a submit event on the form when the user presses enter while focused on an element (standard behavior for input elements wrapped in a <form> tag), but when I press enter, nothing happens (fiddle). If I remove all but one input element, the code works, and I get the expected behavior of pressing enter and triggering a form submit (fiddle).
How do I get the desired behavior (pressing enter submits the form) in the first example where I have multiple forms?
Note: I have found this same behavior in Safari 5.1, Chrome 17, Firefox 9, and IE 9.
Clarification: I know I can just throw some Javascript at it, but I'd like solve it with just markup.
Update: as some of you have helpfully pointed out, I can get the desired behavior by adding an <input type=submit>. The problem is I don't want the user to see the submit button. I can't just set its display to none, because then browsers won't submit when return is pressed, so I borrowed from QUnit and set the following:
HTML:
<input type=submit class=hide-me />
CSS:
.hide-me {
position: absolute;
left: -10000px;
top: -10000px;
}
I have noticed that forms don't like to submit without a submit button. The problem is simply resolved by adding a submit button. See this fiddle for a demonstration. Furthermore, browsers submit when a user presses enter by default, so fix that and you won't need a javascript trigger to cause it.
EDIT:
If you don't want to use a <input type="submit"> simply because it's styling deficiencies, consider a <button type="submit">, it should also do the trick. If you just don't want a submit button at all, stick with the CSS hack.
After trying it myself I couldn't believe it either.
Looks like this is the issue:
Why does forms with single input field submit upon pressing enter key in input
It's default behaviour for browsers to automatically submit simple forms (like search ones) which is why it's working when there is only one input. I believe if you want this functionality on complex forms you will need to use javascript. If you're not against using jQuery the following should do the trick.
$(function(){
$("#formid input").keypress(function(event){
if (event.which = 13){
$("#formid").submit();
}
}
}
Add an element
<input type="submit" name="xx" value="submit" />
it will trigger submit behavior automatically.
you can also use jQuery to handle press event.
Sean.
Try this one. i use this on my textarea with tinymce for a chat system
<script>
function getKeystroke(e)
{
var keynum;
keynum = (window.event) ? event.keyCode : e.keyCode;
switch(keynum)
{
case 13: /* enter key */
document.getElementById("s_say").click();
document.getElementById("s_message").focus();
break;
}
}
</script>
s_say is the ID of the input type submit btn.
Related
This question already has answers here:
Difference between <input type='button' /> and <input type='submit' />
(4 answers)
Closed 1 year ago.
Is there a difference between a button with type="button" vs type="submit"? Are there functional differences, or is it just a descriptive name for easier code reading?
Is this different than input?
From MDN:
type
The type of the button. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
As for the difference between button and input:
A button can have a separate value as data, while for an input the data and button text are always the same:
<input type="button" value="Button Text"> <!-- Form data will be "Button Text" -->
<button type="button" value="Data">Button Text</button>
A button can have HTML content (e.g. images), while an input can only have text.
A button may be easier to tell apart from other input controls (like text fields) in CSS. Note backwards browser compatibility.
input {
}
button { /* Always works */
}
input[type=button] { /* Not supported in IE < 7 */
}
A button with type "button" won't submit a form but one with no type or type=submit (the default) will. Buttons with type=submit are nearly the same as inputs with type=submit but buttons are able to contain HTML content.
<input type="button" />
buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.
<input type="submit">
buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.
when form submit by below code, We should use type=button instead of type=submit to prevent form submit twice.
#using (Html.BeginForm("View", "Controller", FormMethod.Post, new { id = "signupform" }))
{
//Form elements
}
Buttons can be stylized much better than inputs can be used for anchor tags(links).
Images
Content etc.
Inputs can achieve the same functionality as buttons but uglier design.
Let's say inputs are oldschool, buttons are cooler.
They have different default behaviour regarding submitting form data to the server
The button has an attribute named "type" and can contain those values:
submit: Has default behaviour of submitting the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
<button type="button"></button> buttons will not submit a form - they don't do anything by default. Button won't submit form on its own.It is a simple button which is used to perform some operation by using javascript whereas Submit is a kind of button which by default submit the form whenever user clicks on submit button.
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>
I have a form with <input type="submit">. In Chrome submit doesn't do anything. On a Network tab in developer tools I see nothing. No errors in developer tools either. Meanwhile, if I do save a page and open a saved page, then after I press submit button, I see something appears in Network tab. This happens in Chrome and Firefox. This works as expected in IE.
Does anybody have a hindsight, what should I look at?
I don't need a direct answer, I only need to know, where should I look at. If someone posts a direction and that'll help me to solve my problem, I'll accept it as a correct answer.
Structure of a page looks like this:
html
head
body
div
div
form
form
form
form
form
input
input
table
table
tbody
tr..td..input type=submit
If you are not using any JavaScript for form validation then a simple layout for your form would look like this:
<form action="formHandler.php" method="post">
<input name="fname" id="fname" type="text" value="example" />
<input type="submit" value="submit" />
</form>
You need to ensure you have the submit button within the form element and an appropriate action attribute on the form element is present.
For a more direct answer, provide the code you are working with.
You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html
Are you using HTML5? If so, check whether you have any <input type="hidden"> in your form with the property required. Remove that required property. Internet Explorer won't take this property, so it works but Chrome will.
I faced this problem today, and the issue was I was preventing event default action in document onclick:
document.onclick = function(e) {
e.preventDefault();
}
Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:
document.onclick = function(e) {
if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}
Hello from the future.
For clarity, I just wanted to add (as this was pretty high up in google) - we can now use
<button type="submit">Upload Stuff</button>
And to reset a form
<button type="reset" value="Reset">Reset</button>
Check out button types
We can also attach buttons to submit forms like this:
<button type="submit" form="myform" value="Submit">Submit</button>
Check if you are using any sort of jquery/javascript validation on the page and try disabling it and see what happens. You can use your browser's developer tools to see if any javascript file with validate or validation is being loaded. You can also look for hidden form elements (ie. style set to display:none; or something like that) and make sure there isn't a hidden validation error on those that's not being rendered.
I ran into this on a friend's HTML code and in his case, he was missing quotes.
For example:
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<input type="text" name="fname" id="fname" style="width:90;font-size:10>
<input type="submit" value="submit"/>
</form>
In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.
Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.
Also, if you have any tags like center, move them out of the form.
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<center> <-- bad
As strange it may seems, it can have an impact.
You can't have a form element as a child (directly or indirectly) of another form element.
If the following does not return null then you need to remove the excess form elements:
document.querySelectorAll('form form');//Must return null to be valid.
check your form is outside the table
So the code that I have so far is:
<fieldset id="LinkList">
<input type="text" id="addLinks" name="addLinks" value="http://">
<input type="button" id="linkadd" name="linkadd" value="add">
</fieldset>
It is not in a <form> and is just as it is within a <div>. However when I type something into the textbox called "addLinks" I want the user to be able to press Enter and trigger the "linkadd" button which will then run a JavaScript function.
How can I do this?
Thanks
Edit:
I did find this code, but it doesnt seem to work.
$("#addLinks").keyup(function(event){
if(event.keyCode == 13){
$("#linkadd").click();
}
});
$(document).ready(function(){
$('#TextBoxId').keypress(function(e){
if(e.keyCode==13)
$('#linkadd').click();
});
});
It is, yeah, 2021. And I believe this still holds true.
DO NOT USE keypress
keypress event is not triggered when the user presses a key that does not produce any character, such as Tab, Caps Lock, Delete, Backspace, Escape, left & right Shift, function keys(F1 - F12).
keypress event Mozilla Developer Network
The keypress event is fired when a key is pressed down, and that key normally produces a character value. Use input instead.
It has been deprecated.
keypress event UI Events (W3C working draft published on November 8, 2018.)
NOTE | The keypress event is traditionally associated with detecting a character value rather than a physical key, and might not be available on all keys in some configurations.
WARNING | The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.
DO NOT USE KeyboardEvent.keyCode
It has been deprecated.
KeyboardEvent.keyCode Mozilla Developer Network
Deprecated | This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
What should I use then? (The good practice)
// Make sure this code gets executed after the DOM is loaded.
document.querySelector("#addLinks").addEventListener("keyup", event => {
if(event.key !== "Enter") return; // Use `.key` instead.
document.querySelector("#linkadd").click(); // Things you want to do.
event.preventDefault(); // No need to `return false;`.
});
There are a js-free solution.
Set type=submit to the button you'd like to be default and type=button to other buttons. Now in the form below you can hit Enter in any input fields, and the Render button will work (despite the fact it is the second button in the form).
Example:
<button id='close_renderer_button' class='btn btn-success'
title='Перейти к редактированию программы'
type=button>
<span class='glyphicon glyphicon-edit'> </span> Edit program
</button>
<button id='render_button' class='btn btn-primary'
title='Построить фрактал'
type=submit
formaction='javascript:alert("Bingo!");'>
<span class='glyphicon glyphicon-send'> </span> Render
</button>
Tested in FF24 and Chrome 35 (formaction is html5 feature, but type is not).
Replace the button with a submit
Be progressive, make sure you have a server side version
Bind your JavaScript to the submit handler of the form, not the click handler of the button
Pressing enter in the field will trigger form submission, and the submit handler will fire.
You could add an event handler to your input like so:
document.getElementById('addLinks').onkeypress=function(e){
if(e.keyCode==13){
document.getElementById('linkadd').click();
}
}
It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.
First of all add jquery library file jquery and call it in your html head.
and then Use jquery based code...
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});
This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage() with your functionality.
$('#addLinks').keypress(function(e) {
if (e.which == 13) {
sendMessage();
e.preventDefault();
}
});
Based on some previous answers, I came up with this:
<form>
<button id='but' type='submit'>do not click me</button>
<input type='text' placeholder='press enter'>
</form>
$('#but').click(function(e) {
alert('button press');
e.preventDefault();
});
Take a look at the Fiddle
EDIT:
If you dont want to add additional html elements, you can do this with JS only:
$("input").keyup(function(event) {
if (event.keyCode === 13) {
$("button").click();
}
});
Do not use Javascript for this solution!!!
Modern HTML browsers today (and in the past) automatically submit the first form submit button they find when the ENTER/RETURN key is pressed by a user. NO JAVASCRIPT NEEDED! Browsers have worked this way for nearly 20 years but new web developers have not bothered to learn about it.
If you have multiple submit buttons in a web page or want more control, pressing the ENTER/RETURN keys will trigger submission of form data when any form field control in the web page that is associated with a submit type button or input has focus by the user, the autofocus attribute is set on any form field/button/input, or when the user tab's into any form field. The submit button for that field will then trigger when the ENTER/RETURN key is pressed. Otherwise, as mentioned above, pressing ENTER or RETURN on the keyboard automatically triggers the first available submit button for that form in the page.
So, instead of JavaScripting this, an easier solution is to just add tabindex=0 on any of your form fields or submit buttons inside a form element then autofocus on the first input control or submit button. Tabindex=0 assigns that input to the page's list of indexed tab order page items, and autofocus shifts focus to any of your form fields, triggering any submit button to respond to the ENTER/RETURN key command. The user can now press "ENTER" on their keyboard to submit the form at any point they like. This also has the advantage that the first form field is focused on and ready for data by the user. An example below:
<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
<label for="username1">Username</label>
<input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
<label for="password1">Password</label>
<input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
<button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>
Stop scripting everything! The browsers have had this native ability for almost 20 years!!
I found w3schools.com howto, their try me page is at the following.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter
This worked in my regular browser but did not work in my php app which uses the built in php browser.
After toying a bit I came up with the following pure JavaScript alternative that works for my situation and should work in every other situation:
function checkForEnterKey(){
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
}
function buttonClickEvent()
{
alert('The button has been clicked!');
}
HTML
Press the enter key inside the textbox to activate the button.
<br />
<input id="myInput" onkeyup="checkForEnterKey(this.value)">
<br />
<button id="myBtn" onclick="buttonClickEvent()">Button</button>
Using pure HTML form:
<form class="my-form" action="javascript:myFunction();">
<button>Submit</button>
</form>
By default, browsers will interpret Enter as submitting a form. <button> by default is type "submit" and accesses whatever is located in the form's action attribute (overridden if button's formaction is present). In this case for simplicity I use a javascript function with the javascript: pseudo-protocol, but it could be javascript event listener or a GET/POST method as in normal forms.
This is the bare bones of what you need. A form id and change the button type attribute to submit. Add the method attribute to prevent a URL change or page reload.
<form id='form1' method='dialog'>
<input form="form1" type="text" />
<button form="form1" type="submit"> </button>
</form>
<input type="text" id="input_id" />
$('#input_id').keydown(function (event) {
if (event.keyCode == 13) {
// Call your function here or add code here
}
});
I am using a kendo button. This worked for me.
<div class="form-group" id="indexform">
<div class="col-md-8">
<div class="row">
<b>Search By Customer Name/ Customer Number:</b>
#Html.TextBox("txtSearchString", null, new { style = "width:400px" , autofocus = "autofocus" })
#(Html.Kendo().Button()
.Name("btnSearch")
.HtmlAttributes(new { type = "button", #class = "k-primary" })
.Content("Search")
.Events(ev => ev.Click("onClick")))
</div>
</div>
</div>
<script>
var validator = $("#indexform").kendoValidator().data("kendoValidator"),
status = $(".status");
$("#indexform").keyup(function (event) {
if (event.keyCode == 13) {
$("#btnSearch").click();
}
});
</script>
This bug/feature cropped up in one of my pages when viewed in google chrome so i wrote a test page which looks like this
<body>
<form action="loginhandler.php">
<input type="text" id="name">
<input type="text" id="lastname">
<input type="button" value="Login">
</form>
</body>
Here you can see, the input type is NOT of type submit. So if you press ENTER KEY on IE,Firefox,Opera, nothing happens and that is the expected behavior.
But if you press enter on chrome, it SUBMITS regardless of whether the input type is submit or not.
My question , is this a default feature/bug of chrome or am i doing something wrong here. ?
To cite section 4.10.21.2 of the HTML5 specification:
"If the form has no submit button,
then the implicit submission mechanism
must just submit the form element from
the form element itself."the form element itself."
Therefore I believe Chrome's behaviour to be correct, although I think other browsers do this as well. You can catch/block/process form submission by listening to the "submit" (e.g. to block it) event.BlockquoteBlockquotethe form element itself."
Not even Chrome, most of browsers submit once you press enter (even there is not submit button) when cursor in input.
I have the opposite problem. I use custom js-element for my form and when i use style='dispay:none;' for the submit button, chrome does not submit form on enter, although, firefox does :(