Javascript: Invoke function directly or dispatch event? - javascript

Where we have js code that submits a form instead of just submitting the form like:
form.submit();
Should we instead dispatch a (bubbling, cancelable) event in order to allow other potential js event listeners the chance to handle the form submission:
form.dispatchEvent(new Event('submit', {bubbles: true, cancelable: true}));
It seems like this allows our code to play more nicely with others. If this is true, why isn't this pattern pushed more?

HTMLFormElement.requestSubmit() to the rescue!
In most cases in which a form is to be submitted programmatically via JavaScript, it's wise to use requestSubmit() rather than submit(). Doing so ensures submit handlers will have a chance to handle the submit event. Use submit() only when you want to explicitly submit the form ignoring any registered submit event listeners and form validation.
I was simply not aware of this newer form method.
See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
The HTMLFormElement.submit() method submits a given <form>.
This method is similar, but not identical to, activating a form's
submit <button>. When invoking this method directly, however:
No submit event is raised. In particular, the form's onsubmit event handler is not run.
Constraint validation is not triggered.
The HTMLFormElement.requestSubmit() method is identical to activating
a form's submit <button> and does not have these differences.
And usage notes from https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit
The obvious question is: Why does this method [requestSubmit()] exist, when we've had the submit() method since the dawn of time?
The answer is simple. submit() submits the form, but that's all it
does. requestSubmit(), on the other hand, acts as if a submit button
were clicked. The form's content is validated, and the form is
submitted only if validation succeeds. Once the form has been
submitted, the submit event is sent back to the form object.

Related

form with inline onsubmit is not fired from iframe

I have a form with a inline onsubmit event (that sends a simple alert for testing purposes). That alert fires OK when submiting information from this page.
This form has an iframe which have a button that takes the form parent, and submits it. The "postback" on the parent is firing OK but the alert not.
Maybe I'm doing something wrong because the alert is not firing or it cannot be possible?
Parent Form:
<form name="form1" method="post" action="mipagina.aspx"
onsubmit="javascript:alert('hola');" id="form1">
Iframe JS:
formulario = window.parent.document.forms.item(0);
formulario.submit();
That's the normal behavior. From MDN:
The HTMLFormElement.submit() method submits a given .
This method is similar, but not identical to, activating a form's submit . When invoking this method directly, however:
No submit event is raised. In particular, the form's onsubmit event handler is not run.
Constraint validation is not triggered.
The only workaround I may see is:
add your code before formulario.submit();
very bad idea: overwrite document.getElementById('form1').submit method (please avoid this)

event trigger on submit

I want to perform javascript validation after user submits the form. Documentation for jQuery .submit() clearly says:
The submit event is sent to an element when the user is attempting to submit a form.
But if I put
$('form.simple_form.new-channel').submit perform_validation()
into my code, perform_validation() is triggered every time page is rendered! Even when there is no form on it and no 'submit' button. What is the correct way to call a function after submitting a form?
I believe You dont want to trigger action after submitting, You just want to run it after user clicks submit button.
Wouldn`t it work put like that?
$('form.simple_form.new-channel').submit(function(e){
if(!perform_validation()){
e.preventDefault(); //prevents form from being submitted if validation fails
return; //exits function
}
})
Your perform_validation function should then return Boolean value.
EDIT:
You wrote Your function like this:
$('form.simple_form.new-channel').submit perform_validation()
which is exact the same as writing:
$('form.simple_form.new-channel').submit;
perform_validation();
In Your version script just runs the perform_validation() because it isn`t inside event handler.
You could also do it this way:
$('form.simple_form.new-channel').submit(perform_validation);
This one tells the script to run on the form submit, the function which name is passed as an argument.
The problem is your syntax.
$('form.simple_form.new-channel').submit perform_validation()
Because of javascript's liberality the fact that you are not invoking submit here and you have no semicolin after perform_validation... causes no error, but simply invokes perform validation as if it was on the line all by its self with a semicolin.
to correct this, do this
$('form.simple_form.new-channel').submit(perform_validation);

HTMLFormElement submit and reset methods relation with event handlers

The HTMLFormElement DOM interface provides the .submit() and .reset() methods, which I'm heavily making use of in my single-page app.
Right now I'm trying to figure out the relation between these two methods and triggering the form element's onsubmit and onreset event handler methods.
Test case
So considering this perfectly valid HTML5 document:
<!DOCTYPE html>
<title>HTMLFormElement method-event relation test page</title>
<form style="border:solid">
<input name=foo>
<button>Submit</button>
<button type=reset>Reset</button>
</form>
<button id=js-submit>.submit()</button>
<button id=js-reset>.reset()</button>
And the following JS <script> content right below the form:
(function() {
var qs = function(s) {
return document.querySelector(s);
},
form = qs('form');
form.onsubmit = function(e) {
console.log('onsubmit fired');
return false;
};
form.onreset = function(e) {
console.log('onreset fired');
return false;
};
qs('#js-submit').onclick = function() {
form.submit();
};
qs('#js-reset').onclick = function() {
form.reset();
};
}());
Live demo
* Side-note: I know addEventListener may be preferred over onevent handlers, however it'd have the same effect and this is merely a simple, IE8-compatible illustration.
Clicking the Submit and Reset buttons inside the form fire the corresponding onsubmit and onreset methods just fine, as these are user actions the event handlers must be triggered.
The buttons outside of the form call the form element's .submit() and .reset() methods, that is, the methods which I'm programmatically calling in my real code.
Normally, as I'm programmatically calling simple form methods from code-side, I'd expect these to not trigger any form event.
However, clicking the .reset() button does dispatch an onreset event to the form, while .submit() does not dispatch any event to the form. Tested in Chrome, Firefox and IE8.
* The behavior is the same when using addEventListener instead of on* handlers.
Question
Is there a standard expected behavior for whether event handlers will be triggered when a form's .submit() and .reset() methods are called?
The .submit() method is not warranted to (and most often does not) trigger the onsubmit event due to historical reasons. It is worth noting that modern browsers (latest Chrome, Firefox, Opera, Safari and even IE8) do not trigger the onsubmit event when calling form.submit().
The .reset() method in the other hand, follows the spec and performs the same action as clicking a reset button, which includes dispatching the onreset event to the form. Tested in the same browsers as the paragraph above.
Reference
HTMLFormElement.submit MDN page:
The form's onsubmit event handler (for example, onsubmit="return
false;") will not be triggered when invoking this method from
Gecko-based applications. In general, it is not guaranteed to be
invoked by HTML user agents.
DOM Level 2 Recommendation:
Methods
reset
Restores a form element's default values. It performs the same action as a reset button.
submit
Submits the form. It performs the same action as a submit button.
[...]
Note: The onsubmit even handler is not guaranteed to be triggered when invoking this method. The behavior is inconsistent for historical reasons and authors should not rely on a particular one.
W3C mailing list:
submit
Submits the form. It performs the same action as a submit button.
I don't think the last sentence is correct. Using a submit input will
trigger onsubmit. The submit method will not. [...]
The accepted answer remains valid in 2022.
I just wanted to add a note, that there are still inconsistencies between browsers today.
For example if you dispatch a custom event named reset on a form element, chrome will ignore it, but firefox will actually reset the form as if you called form.reset() or clicked a reset button.

HTML 5 form submit handler called even if form is invalid

I'm writing some unit tests for an HTML 5 app that uses the HTML 5 form validation API. I've attached a submit event handler to the form that does some custom handling before serializing to JSON and passing it off to my server.
What I've discovered, though, is that if I initiate a jQuery submit() event on the form, even if it's invalid, my submit handler still gets called.
Instead, I'd expect my event handler not to have been called because the form is invalid.
I've created a JSFiddle to demonstrate (tested in Chrome 20):
http://jsfiddle.net/jonbca/SYg4h/22/
So, what gives?
Triggering the ".submit()" handler simply does not have anything to do with the HTML5 form validation mechanism. That mechanism is really quite independent of JavaScript, and in fact it's mostly unavailable from the DOM API. You can explicitly call "checkValidity()" on a form element, but that just returns a boolean result and does not do any of the visual form updates that happen when the user clicks a "submit" form control.
It's important to keep in mind that many of the fancy HTML5 "smart markup" behaviors are designed to allow things to happen without the need for JavaScript.
Try triggering the submit button:
$('#submitBtn').click();
If you don't have one, just do a hidden one, that replicates the action.
Fiddle: http://jsfiddle.net/SYg4h/30/
Try using a click handler on the button
$('#myform').submit(function (e) {
// check for validation here
var value = $('#foo').val();
if (!value || value == undefined)
$('#message').html('It did not submit');
else
$('#message').html("It submitted");
return false;
});
$('#submitBtn').click(function(){
$('#myform').submit();
});
Try this: http://jsfiddle.net/Cqzcu/4/

Difference between .ajaxSubmit() vs .submit()

Is there a difference between .ajaxSubmit() and .submit()? Has .submit() replaced .ajaxSubmit()?
There's no such function as .ajaxSubmit in jQuery. It's a function used by the jquery form plugin. The difference is that .ajaxSubmit uses AJAX to submit the form whereas .submit, which is part of jQuery, triggers the submit event of the form and eventually submits it synchronously (unless you have subscribed to the submit event of the form and perform some other actions).

Categories

Resources