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
});
Related
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...
My question is about react, onSubmit and preventDefault.
I've got a form, which handles between 2 - 4 steps of user input depending on certain cases.
<Form>
{StepRendersHere}
</Form>
The form has a onSubmit event that prevents default (and stopPropagation).
When using the button for "next step" the event fires, and the form is NOT submitted.
But when using the enter key, the event is fired, but the form is posted. This results in the site refreshing with the form data as url parameters.
The weird thing is that if none of the buttons in the form has type="submit". The onSubmit doesn't even fire on enter key.
isDefaultPrevented returns true in both cases.
Any hints/thoughts on how I can prevent the form from posting when pressing enter? My issue is with Enter key posting the form, despite preventDefault.
Have tried binding the enter key to a event that prevents default, doesn't work. Might have done it the wrong way though.
UPDATE (implementation)
<Form onSubmit={this.inc_step} id="applicationform">
{FormStepRenderedHere}
</Form>
inc_step = e => {
e.preventDefault();
e.stopPropagation();
alert( e.isDefaultPrevented() )
let new_step = this.state.current_step + 1;
alert('INSIDE INC STEP');
if (this.validateForm()) {
this.setState({
current_step: new_step
})
}
}
UPDATE (FIXED IT)
I found a solution, and want to share if anyone else has the same problem.
My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.
Thank you for the comments!
A much easier way to accomplish this is to add a button element to your form and add the display none css attribute (if you don't want to see the button).
The button automatically adds the ability to use the enter key with onSubmit.
I found a solution, and want to share if anyone else has the same problem.
My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.
So actually not rendering the form as a form to begin with was the solution.
I have a third party form to track users on the page. I need to track all page submits on the page including submit fails due to js validations. Broad structure is as following:
<form>
//Elements
</form>
<a id="btnSubmit"></a>
I do not have control over structure of the form. To track the form submits I am using anchor tag click event: $('#btnSubmit').click(function () { //my code });
I am not using form.submit as the js code used in form validation prevents form.submit event from being called. It works well with click event except when user submits form with enter key.
How can I track enter key form submit without form.submit?
You could try listening for the enter key being pressed on one of the input fields, or whatever suits in your form
$('input').keypress(function(e) {
if(e.which == 13) {
//your submit code
}
});
instead of click you can do is use the event "submit" for it.
Please look at the link https://api.jquery.com/submit/ for more details.
I apologise in advance for not being able to provide any actual code, as the problem appears in a page which is currently private :-/ Please bear with me.
I have an HTML form. I attached a (proprietary) calendar widget to one of the text input fields. When the user tabs into the field the calendar appears. On the calendar there are a couple of buttons (to move to the previous/next month). When the user clicks on one of these buttons the calendar updates itself accordingly, but also - the form submits! There's NOTHING in the calendar code that touches anything other than the calendar itself and the text input field it is attached to, let alone submits a form! I would appreciate any clue regarding any of the following questions:
1) What could possibly have submitted the form in such a setting?
2) What things generally submit a form, other than clicking on the submit button or hitting the enter key? (In particular, do ordinary buttons submit forms? Under which circumstances?)
3) As a workaround in case I don't manage to figure this out, is there a way to simply totally disable submitting the form (and then reenable it in an event handler attached to the submit key)?
Note(s): The calendar behaves normally other than that - responds normally to key events and to click events on the dates themselves (which are not buttons). I tried this on both Firefox and Chrome and got the same behaviour. I tried to follow the click event handler step-by-step with FireBug, and everything seemed perfectly normal - but the moment it finished the form was submitted (and the page reloaded). The widget uses jQuery 1.7.2. Any help in understanding and/or solving this will be most appreciated!
Sorry to answer my own question, but none of the given answers was complete, even though I've learnt from them and from the comments! Thanks for everyone who participated!
So:
1+2) Buttons defined by the <button> element cause submits (as if they had type="submit" set. At least in some browsers). If one wants a button not to cause a submit one should use <button type="button">, or the good old <input type="button" />.
3) (Unnecessary for me now, but it was part of the question.) There are many ways to prevent a form from submitting. Three of them are:
to handle the onsubmit event, preventing the submit (by return false; or - preferably! - by e.preventDefault();) in case a flag is not set; set the flag when handling the event(s) that should actually submit the form
to handle the onsubmit event and prevent the submit as above if the element that triggered the event is not (one of) the element(s) we want to cause a submit
to set the form action to non-action, i.e. action="#", and to have the handler for the event that should actually submit the form set the action to the proper address
The calendar can submit your form in its JavaScript source code by calling form's submit() method using jQuery or plain JavaScript.
Here is an example how to disable the form submit and allow it only in case of pressing the button.
<form id="form">
<input type="text" />
<input type="button" name="submit-button" value="Submit"/>
</form>
<script type="text/javascript">
var form = document.getElementById('form'),
button = form['submit-button'];
form.onsubmit = function(e) {
return !!form.getAttribute('data-allow-submit');
};
button.onclick = function() {
form.setAttribute('data-allow-submit', 1);
form.submit();
};
</script>
Demo
The calendar code isn't calling submit() somewhere?
3) As a workaround in case I don't manage to figure this out, is there a way to simply totally disable submitting the form (and then reenable it in an event handler attached to the submit key)?
Unfortunately, I'm not totally sure if it's reliable that the click handler will be called before the form submit event.
( function () {
var prevent_submit = true;
$( "form" ).on( 'submit', function ( event ) {
if ( prevent_submit ) {
event.preventDefault();
}
} );
$( "input[type='submit']" ).on( 'click', function ( event ) {
prevent_submit = false;
} );
} )();
or
$( "form" ).attr( { action : "#", method : "post" } );
$( "input[type='submit']" ).on( 'click', function ( event ) {
event.target.form.action = "...";
} );
Hitting enter on text fields can sometimes trigger a form submit. See here. Especially if that is the only element in the form. One way to control the post back is to set the action to empty and fire off the event yourself with Javascript.
Check the placement of the closing form tags. I had this problem once and I finally figured out that there was some 'permissions' code within the form itself that prevented the user from reaching the closing tag because he didn't have the proper permission level to submit it. In effect this left an open form tag that then responded to other buttons elsewhere on the same page.
I am looking for the neatest way to create an HTML form which does not have a submit button. That itself is easy enough, but I also need to stop the form from reloading itself when submission-like things are done (for example, hitting Enter in a text field).
You'll want to include action="javascript:void(0);" to your form to prevent page reloads and maintain HTML standard.
Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.
Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?
Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:
onKeyPress="if (event.which == 13) return false;"
For example:
<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
an idea:
<form method="POST" action="javascript:void(0);" onSubmit="CheckPassword()">
<input id="pwset" type="text" size="20" name='pwuser'><br><br>
<button type="button" onclick="CheckPassword()">Next</button>
</form>
and
<script type="text/javascript">
$("#pwset").focus();
function CheckPassword()
{
inputtxt = $("#pwset").val();
//and now your code
$("#div1").load("next.php #div2");
return false;
}
</script>
When you press enter in a form the natural behaviour of form is to being submited, to stop this behaviour which is not natural, you have to prevent it from submiting( default behaviour), with jquery:
$("#yourFormId").on("submit",function(event){event.preventDefault()})
Two way to solve :
form's action value is "javascript:void(0);".
add keypress event listener for the form to prevent submitting.
The first response is the best solution:
Add an onsubmit handler to the form (either via plain js or jquery
$().submit(fn)), and return false unless your specific conditions are
met.
More specific with jquery:
$('#your-form-id').submit(function(){return false;});
Unless you don't want the form to submit, ever - in which case, why
not just leave out the 'action' attribute on the form element?
Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.
If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.
Try preventDefault() method inside event listener for submit in this form