submit event does not fire if submit initiated programmatically - javascript

I have a HTML form with button:
<form action="/" method="post" id="MyForm">
<input type="hidden" name="Field1" value="Value1" />
<input type="hidden" name="Field2" value="Value2" />
<input type="submit" name="name" value="submit" />
</form>
I have event handler for submit attached to Window:
window.onsubmit = function()
{
alert("Submit happening!");
};
This event handler fires properly if I click "Submit" button.
However events never works when submit is triggered programmatically from javascript:
$("#MyForm")[0].submit();
How to catch submit event handler when it was initiated by Javascript, not by User click?
I tried to subscribe for Form event using Jquery or AddEventListener - does not work.

That's because you shouldn't just use the submit function, but trigger the submit like:
$("#MyForm").trigger('submit');

Browsers don't fire the form's onsubmit handler when you manually call form.submit().
jQuery also mimicks used to mimick that (see this "wontfix" "bug" report).
See also:
Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?
JQuery: on submit doesn't work

Related

How do I know what caused a form submission?

<form name="myForm" id="a" action="/action_page.php" method="post">
Name: <input type="email" name="fname">
</form>
<button type="submit" form="a" >submits</button>
<script>
const form=document.querySelector('form');
form.addEventListener('submit',function(e){
e.preventDefault();
console.log('a',e.currentTarget);
console.log(e.target);
},true);
</script>
e.target is 'form' itself on clicking on the button whereas according to what I have understood it should be button.
I checked for other events like invalid and click,it works perfectly fine.
Is it because of some submitter?
You aren't listening to the click event of the button, you are listening to the submit event of the form, that's why you see the form as target of the Event.
The submit event is not necessarily emitted on the submit button click, it could also be emitted by pressing ↲ in a form input field (but not on a programmatic submission: see HTMLFormElement.submit())
Luckily, what caused the form submission is available in the SubmitEvent.submitter property:
document.querySelector('form').addEventListener('submit', e => {
console.log(e.submitter);
e.preventDefault();
});
<form>
<input placeholder="Type Enter here!">
<button>Submit</button>
<button>Just another submit button</button>
</form>

How to prevent form submission when invoked by HTMLFormElement.submit() [duplicate]

I am replacing some jquery codes with vanilla js, and I am having trouble with the form submit event listener
<!-- html -->
<form name="myForm">
<input type="text" name="name" />
<button type="button">Click me</button>
</form>
/* jquery code that works */
$myForm = $("form[name=myForm]")
$("form button").on("click", function(e){
$myForm.submit()
})
$myForm.on("submit", function(e){
e.preventDefault()
console.log("Submitting form")
})
/* vanilla js replacement */
myForm = document.querySelector("form[name=myForm]")
myForm.querySelector("button").addEventListener('click', function(){
myForm.submit()
})
myForm.addEventListener('submit',function(e){
e.preventDefault()
console.log("Submitting form")
})
In the vanilla js, the form submit event listener does not seem to be triggered when the form is submitted programmatically. How do I fix this?
A form's submit event listener won't be triggered when you use the .submit() method on the HTMLFormElement:
The submit event fires when the user clicks a submit button (
or <input type="submit">) or presses Enter while editing a field (e.g.
<input type="text">) in a form. The event is not sent to the form when
calling the form.submit() method directly.
- MDN
You can use the .requestSubmit() method instead, which does trigger the onsubmit event handler of the form and performs constraint validation on the form:
/* vanilla js replacement */
myForm = document.querySelector("form[name=myForm]")
myForm.querySelector("button").addEventListener('click', function() {
myForm.requestSubmit();
})
myForm.addEventListener('submit', function(e) {
e.preventDefault()
console.log("Submitting form");
})
<form name="myForm">
<input type="text" name="name" />
<button type="button">Click me</button>
</form>
The main downside to this method is that, unlike jQuery's .submit() method, requestSubmit() has weaker browser support.

jquery: How to detect if a form button was triggered directly or indirectly

I have a form with some elements and one or more submit buttons.
I have an event handler attached to the submit button via jquery to listen for "click".
<form>
<input type="text" name="text" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
$("body").on('click', 'input[type="submit"]', function(e) {
// explicitOriginalTarget is unsupported in IE!!
if (e.originalEvent.explicitOriginalTarget === this) {
alert('direct');
return false;
}
alert('indirect');
return false;
});
Example on JSfiddle
This handler will be triggered by either clicking the button with the mouse or hitting the enter key when the text-input or the button is highlighted.
Question: How can I detect (cross-browser, including IE10+) if the handler was triggered by hitting the enter key when the cursor is in the text-input or by direct click via mouse or enter when tabbed to the button?
Solutions without additional handlers for keypress/keyup are preferred ;-)

Simple function onSubmit?

I'm trying to call a simple function onsubmit. I tried using onsubmit and also a listener with jQuery. My problem is that when the user presses enter he gets redirected to mysite.com?
<form id="teleport">
<input id="tInput" type="text" value="Type a location" />
<input type="button" id="tSubmit" value="Submit"/>
</form>
$("#teleport").submit(function () {
teleport(document.getElementById('tInput').value);
});
How do I prevent anything from happening when submitting? Also .submit() is only detecting the enter key, how do I listen for both enter key and clicks on the submit button?
You need to prevent the default action of the form. You can do that with event.preventDefault():
$("#teleport").submit(function (e) {
e.preventDefault();
teleport(document.getElementById('tInput').value);
});
Alternatively, you could return false inside the submit event handler for the same effect.
The easiest way to make the button submit the form too will be to change it's type to submit:
<input type="submit" id="tSubmit" value="Submit" />
Or you could attach a click event handler to your current button and trigger the submit event of the form.
Prevent submiting a form:
$("#teleport").submit(function (e) {
teleport(document.getElementById('tInput').value);
e.preventDefault();
});
Submit event catches any way of submitting a form - both with clicking the submit button and enter key press.

trigger Ajax xmlhttp function when submitting form

I would like to trigger an ajax call/object instantiation when i submit a form. Can i do this vie the action="" field?
<FORM id="form" METHOD="GET" ACTION="">
<b> Enter argument: </b>
<input size="40" name="q" id="q" value="">
<INPUT TYPE="submit" id="q" VALUE="Submit">
<INPUT TYPE="reset" VALUE="Reset">
</FORM>
in the same same file i have a function:
function xmlhttpPost(){
...
request = new ajaxRequest()
...
request.open("GET","xmlget.php?url=" + $search + nocache, true)
Add an onclick handler to the submit button, like so:
<INPUT TYPE="submit" id="q" VALUE="Submit" onclick="someJavaScript()">
Have a look at form's onsubmit event.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
You can attach an event handler to the form's submit event, and then make your ajax request in the event handler.
You should use onsubmit="function();" Also once you get this working you will also have to prevent the form from submitting according to the "action" jQuery provides event.preventDefault(); which works the best from what I've seen.

Categories