What triggers the onsubmit event? How to configure that? - javascript

Naively you might assume that the event is triggered that when the (a?) input button of type "submit" is clicked.
In fact, as far as I'm able to ascertain, every button within a form triggers the event.
Is there some way to set a button to not trigger the event?

every button within a form triggers the event
No. Only submit buttons do. (As well as a few other cases such as when the Enter key is pressed in a text input).
Note that <button> elements are type="submit" by default and should be type="button" if you want a non-submit button for handing JS from.
You can also attach a JavaScript click event listener to a button and call preventDefault on the event object.

Button's default type is submit. If you want buttons that don't submit, you have to change their type to button.

Related

How does preventDefault and type submit work with forms?

So I tried a couple of things when I using JS and try submitting inputs, and there are odd things I didn't understand the logic.
There is a difference between <input tpye="submit/> inside and outside of <form> tag. If it's inside the form tag I need to use preventDefault() function, but if it's outside form tag I am not required to do that if write simple js vanilla code.
Why is that?
What the difference between onsubmit and onclick ? especially in a form tag. Because If I use onsubmit the js code doesn't really work.
If I use preventDefault(event) it's preventing from the form to be sended into a server, and instead it doing the calculations with the browser only ?
Thanks !
By default, if you have an input of type "submit" in a form then clicking that input (or hitting enter after filling in ANY inputs in the form) will send a post or get request to the server, redirecting the current page to the server's response.
This was the original way to submit form data to a server, without using javascript. If you want to prevent this from happening, you can either replace the submit input with a plain button (<button onclick="doSomething()">Submit</button>), or prevent the default submission event: (form.onsubmit = event => event.preventDefault()).
The difference between onsubmit and onclick is that onsubmit only fires when a submission event is emitted from the form. To emit a submit event, the form needs an <input type="submit"> to be clicked, or for the user to trigger a submission by hitting enter.
Another way to prevent this default behavior is to return false in the submission handler.
onclick only gets fired when an element is clicked. Because events in javascript propagate up to parents, this will also trigger any onclick handlers on all parent elements.
If you want to completely ignore the default form submission behavior, then you can define a button with an onclick handler to handle your custom submission logic.
If you have a type="submit" input (Note, The default value for the type attribute of button elements is "submit") inside a form, the default action on click is to submit that form. To prevent it from submitting, place the button outside the </form>. This works because the button doesn't refer to any form to submit. You can instead, add a listener and call event.preventDefault(). This works because you are telling the browser NOT to take the default action (submitting the form)
onsubmit is used mostly on <form> elements. It triggers right before the form is submitted regardless of how it is submitted. onclick can be emitted from just about any element. It occurs when you click on an element. This could be on an <input>, a <button>. or even an entire <form>
Don't use this.

How to prevent double click in redux-form?

I have a form and some buttons which are not related to the form. Also I have a blur validation on fields of the form. When field of the form is focused and I'm clicking on none-form button first time I fire blur action of redux-form field. And only on second click the button onClick is working. I want to fire onClick of none-form button on first click(when redux-form field blur action is firing). What should I do?
UPD: So far the best option is to replace onClick with OnMouseDown

Submit event on input field in a form

Came across a code in which the submit() event has been applied to the input field in the form.
Something like:
$("#foo").click(function(){
$("#formID input").submit();
})
where "#foo" is a dynamically created list element. Does this submit only the input field and not the entire form?
Since it is being called without any arguments, it will trigger a submit event.
This will bubble and trigger any submit event handlers on that element and any of its ancestors.
It will not trigger any native submission of data (that would require the method to be called on a form element).

Enter triggers button click

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...

Why does $.change() fire on a submit button?

I have a $.change() event, but when a submit button is pressed, the change event fires again. It is only supposed to fire once when a text is inputted into a input text box.
$('input:submit', top.document).bind('click', function (e) {
alert("submitting")
});
$('input').change(function (e) {
alert("fire");
});
Edit: For whatever reason, a change event is invoked when the input button is clicked. (thanks Anthony)
The way to fix this is simply don't select the submit button.
You can try
$('input:text')
To select only text fields.
Or you can do
$('input:not(:submit)')
To select all input elements except the submit button(s).
Read about selectors here
Edit: Using <button> instead won't work. It still counts as an input field, but it's value is separate from the text displayed on the button.
$('input').change(function(e){ alert("fire") }); applies that event to ALL input elements, including <input type="submit".../>. If you really want EVERY SINGLE text input element to have a change event, you want ``$('input[type=text]').change(function(e){ alert("fire") });` Otherwise, it might be best to use an id or class.
#Mark,
You are spot on and I'd edit you if I could to help out. Maybe someday soon...
#ajowi,
Submit buttons are inputs. At least most of them are:
<input type="submit" />
So Mark,it's not that they are doing anything with the button text, it's that the input, which is a button, is being changed by act of clicking on it.
So his solutions were great. Go with
$("input:text").change

Categories