submit event not captured while submitting via javascript - javascript

The problem I encountered is that I have no idea why the submit event cannot be caputred if the form is submitted via Javascript.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form id="formA">
<input type="text" id="name" value="test"/>
<input type="button" id="btn" value="submit by js"/>
<input type="submit" id="btn2" value="submit directly"/> <!-- event can be triggered -->
</form>
</body>
<script type="text/javascript">
document.getElementById("formA").addEventListener("submit", function() {
console.log("form is submitted"); // no effect if submitting by js. WHY?
});
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("formA").submit();
});
</script>
</html>

I believe this is the correct answer:
It is the expected behavior of the form:
The submit method does not invoke the onsubmit event handler.
Reference: Microsoft - Event handler parameters
In other words, when the form is submitted programmatically the onsubmit event will not trigger. It's only triggered when the submit button is clicked. And this is what I observed when I tested OP's code.
OP also outputs a message to the console to test if the form has been submitted. However, console persistence would need to be enabled to see this message. If not enabled, the console log will get cleared when the form is submitted (making it appear that no message was printed).
document.getElementById("formA").addEventListener("submit", function() {
console.log("form is submitted");
});

You can apply trick to capture submit event on button click, when button client you can add click event on submit, it would also work same that you want to achive
document.getElementById("formA").addEventListener("submit", function() {
alert("form is submitted"); // no effect if submitting by js. WHY?
});
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("btn2").click();
});
<form id="formA" name="formA" action="#">
<input type="text" id="name" value="test" />
<input type="button" id="btn" value="submit by js" />
<input type="submit" id="btn2" value="submit directly" />
<!-- event can be triggered -->
</form>

Related

Find out which html form was submitted

Assume I have many html forms in a website. I need to find out which html form was submitted.
$("form").submit(function(event){ }
Using the function above, can i find out which form was submitted?
You should assign an identifiable attribute to the form and use event.target to access that attribute.
In this case, I've assigned name to each form and printed the name on the console when the form is submitted.
$("form").submit(function(event) {
event.preventDefault();
console.log(event.target.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1">
<button type="submit">submit</button>
</form>
<form name="form2">
<button type="submit">submit</button>
</form>
<form name="form3">
<button type="submit">submit</button>
</form>
Even though it is recommended to use ID, you can do without it. your event.target provides the reference for the form.
$("form").on("submit", function(event){
event.preventDefault();
var a = $(event.target).children("input[type='text']").val();
console.log(a);
});
JSFiddle
Thanks #31piy for reminding about it.
Have a look into link below to identify submission of different forms.
$(document).ready(function() {
$("#Form1").submit(function(event) {
alert($(this).attr('id'));
event.preventDefault();
});
$("#Form2").submit(function(event) {
alert($(this).attr('id'));
event.preventDefault();
});
$("#other").click(function() {
$("#Form1").submit();
});
$("#other2").click(function() {
$("#Form2").submit();
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<form id="Form1" action="destination.html">
<input type="text" value="Hello there">
<input type="submit" value="Go">
<div id="other">
Click to trigger the handler for first form
</div>
</form>
<form id="Form2" action="destination.html">
<input type="text" value="Hello there">
<input type="submit" value="Go">
<div id="other2">
Click to trigger the handler for second form
</div>
</form>
</body>
</html>
Good question.
I usually submit every form to a different route handler. This way I manage to keep some basic principles (Single responsibility principle). Otherwise, you risk your code becoming too complicated to read.
If you insist on having the same route and then differentiate in the backend, I believe the other answers will give you answer your question.

Form Submit Button Do not work

I have a form with a submit button. Unfortunately my javascript function does not work. Where is my mistake? It works by pressing enter but not by clicking on the submit button
<div id="form" class="contact-us-form">
<form id="myform" target="_self" onsubmit="" action="javascript: postContactToGoogle()">
<div>
<input spellcheck="false" autocomplete="off" id="email" type="text" name="email" value="deine eMail" onfocus="this.value=''" onblur="this.value='deine eMail'">
</div>
<br>
<div>
<button onclick="submits()" id="send" type="submit">EINTRAGEN</button>
</div>
</form>
<script type="text/javascript">
function submits() {
document.getElementById("myform").submit();
}
</script>
</div>
What you're doing is strange. You are trying to do the submission very "manually". The submit button (i.e. the type="submit" part) is already going to submit this form, so there is no need for your function submits().
Afterwards, in javascript, simply refer to your form's submit event. You can get the form by id like your doing already.
Add 'name' attribute in your form
<form id="myform" name="myform">
<!-- Form content -->
</form>
change your script function
<script type="text/javascript">
function submits() {
document.myform.submit();
}
</script>
I found the mistake by myself:
onblur="this.value='deine eMail'"
Do not use onblur in your submit button. It will kill the submit function and it will not work

multiple submit buttons on same form with onsubmit function

I have 3 sumbit buttons in myform and i need different 3 actions based on which buttton it clicked. so i need to write javascript function to do the same. how i can get to know in javascript which button is clicked.
Javascript:
<script type="text/javascript" language="javascript">
function submitform(){
//do something
}
HTML:
form name="myform" method="get,post" onsubmit="return submitform();"
input type="submit" name="submit" value="Home"
input type="submit" name="submit" value="Reschedule"
input type="submit" name="submit" value="Cancel"
Any help will be appreciated
Edit:
You could also have a hidden input which tells you which button was pressed, then handle it on the server. When a button is clicked it will change that input before submitting.
<input type="submit" onclick="javascript:document.getElementById('submitClicked').value='forward';return true;" id="linkName" value="Forward" />
<input type="submit" onclick="javascript:document.getElementById('submitClicked').value='back';return true;" id="back" value="Back" />
Demo: http://jsfiddle.net/Homeliss/vperb/
Note: the demo uses jquery to show a message instead of posting the form, but that is just for demo purposes. The solution is plain javascript
In modern browsers, you can use the submitter property of a SubmitEvent.
function submitForm(submitType)
{
switch (submitType)
{
case 'Submit 1':
console.log('Submit 1');
break;
case 'Submit 2':
console.log('Submit 2');
break;
}
return false;
}
<form onsubmit="return submitForm(event.submitter.value)">
Name: <input name="name" required /><br />
<div>
<input type="submit" value="Submit 1" />
<button type="submit" value="Submit 2">Submit 2</button>
</div>
</form>
If you could use jQuery, then this could be much easier.
One solution however would be to remove the submitform() from the form and add it to the onclick event of each of your submit buttons. This way, you can alter it to pass a parameter denoting which button called it.
Good luck.
we can submit a form once in html pages. So we use only one submit button in a form. But for calling more functions we can use onClick event and input type should be button.
I have a question. is there any other input field inside your form?
If there is another field such as text field, which buttons action will be call when we press Enter inside the text field?
My suggestion is this:
<form name="myform" method="get,post" onsubmit="return false;">
<input type="button" value="Home" onclick="submitform(1)" />
<input type="button" value="Reschedule" onclick="submitform(2)" />
<input type="button" value="Cancel" onclick="submitform(3)" />
</form>
in this code, user must click on a button to submit the form and pressing the enter will not cuse to doing any action.

Before submitting form programmatically

In jQuery-Mobile I'm submitting a form programmatically and I want to capture the submit event to perform some validations before. I have already tried the following solution provided in other questions about jQuery:
$(document).ready(function(){
$('#my_form').bind('submit', function() {
alert('before submit');
...
});
});
But I cannot get the function executed and the alert displayed. Does anyone know any other way to achieve this?
My form is something like:
<form id="my_form" method="POST" action="..." data-theme="b">
And the way I am calling it programmatically, from another section of the same page is like this:
<input type="submit" onclick="document.forms['my_form'].submit(); return false;" value="Submit" data-theme="b"/>
Thank you in advance for your help.
The submit handler of the form is NOT executed when you submit the form programatically.
NOTE: Do NOT use a submit button to programatically submit a form. Instead use button or allow the submission from the submit button to be handled, i.e.
<input type="button" onclick="document.forms['my_form'].submit()" value="Submit another form" data-theme="b"/>
(the above is not correct anyway since it needs the form to have a NAME, not just an ID)
So
<input type="button" onclick="document.forms['my_form_NAME'].submit()" value="Submit another form" data-theme="b"/>
OR
<input type="button" onclick="document.getElementById('my_form_ID').submit()" value="Submit another form" data-theme="b"/>
OR since you have jQuery:
<input type="button" onclick="$('#my_form_ID'].submit()" value="Submit another form" data-theme="b"/>
OR if you can put the button in the form (best way):
<input type="submit" value="Submit THIS form" data-theme="b"/>
But since you want to bind - here is how to submit using another button instead of the better way using the form's own submit button:
<form id="actualForm">...
.
.
</form>
<input type="button" id="subbut" value="Submit another form on this page" data-theme="b"/>
$(document).ready(function(){
$('#subbut').bind('click', function() {
alert('before submit');
...
$("#actualForm").submit();
});
});
If there is hardcoded inline behaviour you cannot change, use the jQuery to remove it too
How can I remove an inline onclick attribute with a bookmarklet?
$(document).ready(function(){
$('#subbut').attr('onclick',""); // or $('#subbut').onclick=null;
$('#subbut').bind('click', function() {
alert('before submit');
...
$("#actualForm").submit();
});
});
Changing the return value of onClick to TRUE does the job:
<input type="submit" onclick="document.forms['my_form'].submit(); return ***true***;" vakue="Submit" data-theme="b"/>

IE7 form not prompted for remember password when submitted through javascript

I have a website where we use Javascript to submit the login form. On Firefox it prompts the user to remember their password, when they login, but on IE7 it doesn't.
After doing some research it looks like the user is only prompted in IE7 when the form is submitted via a Submit control. I've created some sample html to prove this is the case.
<html>
<head>
<title>test autocomplete</title>
<script type="text/javascript">
function submitForm()
{
return document.forms[0].submit();
}
</script>
</head>
<body>
<form method="GET" action="test_autocomplete.html">
<input type="text" id="username" name="username">
<br>
<input type="password" id="password" name="password"/>
<br>
Submit
<br>
<input type="submit"/>
</form>
</body>
</html>
The href link doesn't get the prompt but the submit button will in IE7. Both work in Firefox.
I can't get the style of my site to look the same with a submit button, Does anyone know how to get the remember password prompt to show up when submitting via Javascript?
Why not try hooking the form submission this way?
<html>
<head>
<title>test autocomplete</title>
<script type="text/javascript">
function submitForm()
{
return true;
}
</script>
</head>
<body>
<form method="GET" action="test_autocomplete.html" onsubmit="return submitForm();">
<input type="text" id="username" name="username">
<br>
<input type="password" id="password" name="password"/>
<br>
Submit
<br>
<input id="FORMBUTTON" type="submit"/>
</form>
</body>
</html>
That way your function will be called whether the link is clicked or the submit button is pushed (or the enter key is pressed) and you can cancel the submission by returning false. This may affect the way IE7 interprets the form's submission.
Edit: I would recommend always hooking form submission this way rather than calling submit() on the form object. If you call submit() then it will not trigger the form object's onsubmit.
Did you try putting in url in the href and attaching a click event handler to submit the form and returning false from the click handler so that the url does not get navigates to.
Alternatively hidden submit button triggered via javascript?
You could try using the HTML <button> tag instead of a link or a submit button.
For example,
<button type="submit">Submit</button>
The <button> tag is much easier to style than the standard <input type="submit">. There are some cross-browser quirks but they are not insurmountable.
A really great article about the use of <button> can be found at particletree: Rediscovering the button element

Categories

Resources