I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.
I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:
$('form').keypress( function( e ) {
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
return false;
}
})
As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.
Does anyone know of a more sophisticated technique for doing this?
Similarly, are there any pitfalls to this solution that I'm just not aware of?
Thanks.
Using
<button type="button">Whatever</button>
should do the trick.
The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.
It is important to read the HTML specifications to truly understand what behavior is to be expected:
The HTML5 spec explicitly states what happens in implicit submissions:
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).
Edit to add:
The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.
Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.
I don't think you need javascript or CSS to fix this.
According to the html 5 spec for buttons a button with no type attribute is treated the same as a button with its type set to "submit", i.e. as a button for submitting its containing form. Setting the button's type to "button" should prevent the behaviour you're seeing.
I'm not sure about browser support for this, but the same behaviour was specified in the html 4.01 spec for buttons so I expect it's pretty good.
By pressing 'Enter' on focused <input type="text"> you trigger 'click' event on the first positioned element: <button> or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.
See the example here.
Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.
But why do you need to press Enter in text field? If you want to submit form by pressing 'Enter', but the <button> must stay the first in the layout, just play with the markup: put the <input type="submit"> code before the <button> and use CSS to save the layout you need.
Catching 'Enter' and saving markup:
$('input[type="text"]').keypress(function (e) {
var code = e.keyCode || e.which;
if (code === 13) {
e.preventDefault();
// also submit by pressing Enter:
$("form").submit();
}
});
Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.
You can use javascript to block form submission until the appropriate time. A very crude example:
<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">
<input type='text' name='txtTest' />
<input type='button' value='Submit'
onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />
</form>
Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.
Dom example
<button onclick="anotherFoo()"> Add new row</button>
<input type="text" name="xxx" onclick="foo(event)">
javascript
function foo(event){
if(event.which == 13 || event.keyCode == 13) // for crossbrowser
{
event.preventDefault(); // this code prevents other buttons triggers use this
// do stuff
}
}
function anotherFoo(){
// stuffs.
}
if you don't use preventDefault(), other buttons will triggered.
I would do it like the following: In the handler for the onclick event of the button (not submit) check the event object's keycode. If it is "enter" I would return false.
My situation has two Submit buttons within the form element: Update and Delete. The Delete button deletes an image and the Update button updates the database with the text fields in the form.
Because the Delete button was first in the form, it was the default button on Enter key. Not what I wanted. The user would expect to be able to hit Enter after changing some text fields.
I found my answer to setting the default button here:
<form action="/action_page.php" method="get" id="form1">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
Without using any script, I defined the form that each button belongs to using the <button> form="bla" attribute. I set the Delete button to a form that doesn't exist and set the Update button I wanted to trigger on the Enter key to the form that the user would be in when entering text.
This is the only thing that has worked for me so far.
You can do something like this.
bind your event into a common function and call the event either with keypress or button click.
for example.
function callME(event){
alert('Hi');
}
$('button').on("click",callME);
$('input ').keypress(function(event){
if (event.which == 13) {
callME(event);
}
});
I added a button of type "submit" as first element of the form and made it invisible (width:0;height:0;padding:0;margin:0;border-style:none;font-size:0;). Works like a refresh of the site, i.e. I don't do anything when the button is pressed except that the site is loaded again. For me works fine...
Say we have got a form with an action for example : <form id="form" name="form" action="test.php"> Is there a way to control when will the action occur even if i hit the submit button using Javascript?
you can control it by deciding when you hit the button.
the action attribute of the form tag just dictates what handles the submitted info. For a delay, or other fancy stuff you may want to incorporate some javascript into your front-end design.
here is a link
Try something like this:
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
// other actions
})
})
You should call event.preventDefault() when form submit, it function will cancel sumbmiting of the form, later in your scipt you can sumbit it from Javascript.
Using Javascript, no framework, what button event should I use to confirm form when I wish not redirect? I expect to use either left mouse button or keyboard to confirm the form.
I used this element:
<button type="button" value="1">Save</button>
Using type="submit" with "submit" event is no solution for me because this creates redirection (values the from are lost). So I use type "button".
When I use
document.getElementById("advanced_form").addEventListener("click", saveOptions);
This even "click" is used with mouse. But there is possibility that the user will use keyboard instead mouse to submit form. So I suspect the form would not react to keyboard confirm action. I did not find any event related to button being pressed. So how to solve this problem?
You could still use ´type="submit"´ in combination with ´e.preventDefault();´ to aviod the redirect.
I hope this helped, good luck.
From your clarifying comment:
What happened is when I clicked the button the values which were in the form disapeared and so I understood it that the form was reloaded without any values.
Submitting a form...submits the form. What you get back as a result depends entirely on what the server sends back.
But the values should not disappear, the behaviour which I need is like in a normal Browser Window (WINAPI)
That is normal.
...the page will not clear the values. If I'd want to close the form, I'd close the tab (html page).
That isn't normal. Normal is for the form to go away and be replaced by the result of submitting it.
But you can do that with the submit event, just use event.preventDefault() within the submit event to prevent the form submission:
document.getElementById("the-form").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the form from being submitted
});
That event will reliably fire whether the user used the mouse, keyboard, or assistive technology to submit the form. The click event on a submit button will not reliably fire when the form is submitted with the keyboard or assistive technology.
You can use submit button, but you need to handle submit action. Try this (with jquery):
<input class="submit_button" type="submit" value="Save" />
<script>
function submit_form(e)
{
if (check_form_submit()) {
// check your data here
$(this).submit();
return;
}
e.preventDefault();
}
$(function() {
$('.submit_button').parents('form').submit(submit_form);
});
</script>
You should still use the submit input type but you need to prevent the default action so that the page doesn't reload.
If you are using jQuery this snippet should help.
$('#my-form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
// Your code here
this.submit(); // If you want to submit at the end
});
Is it possible to assign the return key as a shortcut for an anchor. Just like when submitting a form if one of the input fields are on focus.
I have looked a little at the jQuery hotkeys but since I'm lacking some skills in js I can't quite figure it out.
My plan is that when the page loads the user can just press enter. Then an action will be performed followed by a redirect. I'm trying to do this
Reason for doing this is that I believe it's a lot faster for the user to press enter than to move the cursor and click on the link before the actual action takes place.
Much more simple will be to auto focus the link:
window.onload = function() {
document.getElementById("changeStatusLink").focus();
}
No jQuery is required and as it's focused, Enter press will trigger the click event.
If it's a form (e.g. with id #myform) why not to try to trap the user submit using this code. You need to put a hidden form submit element inside the form.
HTML
<form id="myform">
<input type="text" name="email" />
<input type="submit" style="display: hidden;" />
Click here to do some action
</form>
Javascript
$(function(){
$('#myform').submit(function(){
$(this); // this refers to the form
$('#your-link-id').click();
return false;
});
});
See: Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
Note: the code is untested but it should work.
I have some javascript that ends up programatically clicking on a button:
document.getElementById("myButton").click();
This in turn results in the form being submitted using a function call:
<form onsubmit="submit_this_form(this);return false;" action="" method="POST">
It seems that a good percentage of the time either the actual button click is not going through or the form is not being submitted. I think the button click is going through and I know the code is being called because I have a counter embedded and I can see it is executing.
My question is...is there an event or a way to verify that the form actually posted? By the way, I don't have control of the HTML code so I can't change the tag content.
<form onsubmit="submit_this_form(this);return false;" action="" method="POST">
return false after submit_this_form() essentially stops the form from actually submitting. I believe if you change it to:
<form onsubmit="submit_this_form(this);" action="" method="POST">
It should work as you want.
Using return false after an event handler will essentially 'hijack' the default functionality. Basically, whatever your event handler function script does replaces the default behavior, which in this case, is submitting the form data to the server.
I don't think you can verify that form is actually where submitted.
But you can submit it by hand via XMLHTTPRequest and check for server responce.
This way you will be sure thet form is submitted. And you can have an event (your custom event) that says about form submission if you need to...
BTW do not forget to prevent forms default submit if you go AJAX way.
Check jquery.form plugin to make a fast rollout of AJAX form submission and look is it what you want or not.
Good luck!