javascript Submit multiple forms with one button - javascript

In my html I have multiple forms (text inputs, radio buttons, check boxes and select) and one button. I would like to fill all these forms and send values to my php file. For now I am trying to submit values from text input and select but I am stuck at this point.
I have a js submit file:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
And my forms are like this:
SELECT:
<form id ="form1" name="dists" action="solve.php" method="post">
<select id="demo" name="sadzba" onchange="selectElement1(this.value)>
<option value="">-- vyberte oblasť --</option>
</select>
</form>
Text input form + button:
<form id="form2" action="solve.php" method="post">
<input type="text" name="spotVT" ><label>kWh za rok VT</label>
<div id="nt" style='display:none'><input type="text" name="spotNT" ><label>kWh za rok NT</label></div>
</form>
<input id="sub" type="button" value="Ok" style="margin-left:15px;" onclick="submitForms()"/>
But this is not working. Can you help me please? Thank you

Once you are submitting one form your page reloads or terminates the javascript after that submission of form so better use Ajax for submitting multiple forms at the same time
with jquery
$("#sub").click(function(){
$("form").each(function(){
var fd = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "solve.php",
data: fd,
processData: false,
contentType: false,
success: function(data,status) {
//this will execute when form is submited without errors
},
error: function(data, status) {
//this will execute when get any error
},
});
});
});
Above code will submit every form when you click a button with id sub

It will be easier to only submit one form. You can give your select and input tag the same form name by assigning form="your-form-id".

Here's an simple example of a native Javascript implementation.
<!DOCTYPE html>
<html>
<head>
<title>Multiform - JAVASCRIPT</title>
</head>
<body>
<fieldset>
<legend>Form 1</legend>
<form name="f1" id="f1" onsubmit="return validate(this)">
<input type="text" name="username" placeholder="Username" />
</form>
</fieldset>
<fieldset>
<legend>Form 2</legend>
<form name="f2" id="f2" onsubmit="return validate(this)">
<input type="text" name="email" placeholder="Email" />
</form>
</fieldset>
<fieldset>
<legend>Form 3</legend>
<form name="f3" id="f3" onsubmit="return validate(this)">
<input type="text" name="password" placeholder="Password" />
</form>
</fieldset>
<button onclick="submitAll();">SUBMIT ALL</button>
<script>
'use strict';
function validate(form){
//forms processsing goes here...
console.log(form, form.name)
return false;
}
function submitAll(){
for(var i=0, n=document.forms.length; i<n; i++){
document.forms[i].onsubmit();
}
}
</script>
</body>
</html>

You could try this. If submitting all forms is fine for your page
$('form').submit();
Function that's in actual use:
function trySubmitAllForms() {
if ($('.saveSpinner').is(':visible')) {
return;
}
if ($('form').valid()) {
$('.saveSpinner').show();
$('form').submit();
} else {
showValidationErrorMessages();
}
}

Bismillah, try our method below, insyaAllah we hope can provide a solution for you.
document.getElementById("submit").addEventListener("click", function () {
$(function () {
$("#formid01").delay(300).submit();
$("#formid02").delay(300).submit();
});
});

Related

How can I fix my Mturk submit button? It is not working

When I submitted my external HIT on Mturk, the Submit button is not working. I would appreciate if someone could help me with this. The data gets stored in my server though. Here is my code:
<div id="instruction3" class="instructions" style="display:none">
survey questions here
Submit
</div>
function SaveData() {
(some code here)
d = {
"trialStruct": trialStruct,
"critStruct": critStruct
};
console.log(d)
SendToServer(curID, d);
}
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<p><input id="submitButton" type="submit" value="Submit" /></p>
</form>
function SendToServer(id, curData) {
$.ajax({
type : "POST",
url : "https://xxxxxxxxxxxx/turk/save.php",
data : { json : JSON.stringify(curData) },
success : function(data) {
document.forms[0].submit();
}
});
}
Edited: the flow should be participants click on the submit button and the data gets stored and sent to the externalSubmit page. These are parts of the code from Mturk that I need to implement in my code and perhaps I am not doing it right.
<!-- HTML to handle creating the HIT form -->
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<!-- HTML to handle submitting the HIT -->
<p><input id="submitButton" type="submit" value="Submit" /></p>
</form>
You should call the SaveData() function inside the form tag
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form" onSubmit="SaveData()">
So I think you should try to move the SaveData function to the onSubmit value of the form. So you would be submitting the form and the data would get saved to the server. You have extra html code above but I think that is superfluous for what you are trying to do.
function SaveData() {
(some code here)
d = {
"trialStruct": trialStruct,
"critStruct": critStruct
};
console.log(d)
SendToServer(curID, d);
}
function SendToServer(id, curData) {
$.ajax({
type : "POST",
url : "https://xxxxxxxxxxxx/turk/save.php",
data : { json : JSON.stringify(curData) },
success : function(data) {
document.forms[0].submit();
}
});
}
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form" onSubmit="SaveData()">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<p><input onclick="window.location.href = https://workersandbox.mturk.com/mturk/externalSubmit';"id="submitButton" type="submit" value="Submit" /></p>
</form>
Here is the working one, I have used https://postman-echo.com/post just to make sure it works.
function SaveData() {
var d = {
"trialStruct": trialStruct,
"critStruct": critStruct
};
console.log(d);
SendToServer(curID, d);
}
function SendToServer(id, curData) {
$.ajax({
type: "POST",
url: "https://postman-echo.com/post",
data: {
json: JSON.stringify(curData)
},
success: function(data) {
$("#mturk_form").submit();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="instruction3" class="instructions" style="display:none">
Submit
</div>
<form action="https://postman-echo.com/post" id="mturk_form" method="post" name="mturk_form">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<p><input id="submitButton" type="submit" value="Submit" /></p>
</form>

Submit Form With Both Action and Onsubmit Function

My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">

javascript function call for single form

I have multiple forms in my php file for different buttons. So, if I click on Back button, ramesh.php script should be called and so on. This is the code.
<form action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
<form action="update.php" method="post" >
<button type="submit">Update</button>
</form>
However, I need to pass some data to server from my client side on form submit just for the update button. I have a javascript function to send the data to server side as below.
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
var mydata = 3;
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+mydata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
})
</script>
If I click on the update button, the javascript function is working fine. However, if I click on Back or Submit button, I should not be calling the javascript function. Is there someway to do this?
Give your form an id:
<form action="update.php" method="post" id="update-form">
Then use a more specific selector:
$("#update-form").submit(function() {
// Code
});
I'm not quite sure why you need JavaScript to dynamically add data to your form, however. You should just use an <input type="hidden" /> directly.
type=submit will always load the form's action. Try to specify wich form to submit.
<form name="backForm" id="backForm" action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form name="form2" id="form2" action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
Now you can access the form via document.backForm or document.getElementById("backForm") and than use submit(); like document.getElementById("backForm").submit();

submit a form inside another form

I have a form with POST method and an action of another page.
Within the form i have another form that I need to make submit with a different action but its submitting with the main form action.
this is my second form:
<script>
function formSubmit()
{
document.getElementById("invoices_form").submit();
}
</script>
<form action="resend_multiple_invoices.php" name="invoices_form" method="post">
<input type="button" onclick="formSubmit()" value="Send Invoices" />
</form>
how can i get it to submit the second form and not the main one?
You cannot (universally) submit a nested form separately from its parent form. Nested forms are invalid HTML as outlined in the W3C prohibitions.
To solve your problem, I suggest you use two separate forms as follows:
<script>
function invoicesFormSubmit()
{
document.getElementById("invoices_form").submit();
}
function otherFormSubmit()
{
document.getElementById("other_form").submit();
}
</script>
<form action="resend_multiple_invoices.php" name="invoices_form" method="post">
//
// Input fields go here
//
<input type="button" onclick="invoicesFormSubmit()" value="Send Invoices" />
</form>
<form action="other_method.php" name="other_form" method="post">
//
// Input fields go here
//
<input type="button" onclick="otherFormSubmit()" value="Other Method" />
</form>
You can use the 'form'-attribute in your input-fields and then mix all your inputs.
By submitting they refer to the correct form.
<form action="" method="post" id="form1"></form>
<form action="" method="post" id="form2"></form>
<input name="firstname" form="form1">
<input name="firstname" form="form2">
<button type="submit" name="submit" form="form1">Save form 1</button>
<button type="submit" name="submit" form="form2">Save form 2</button>
See also https://www.w3schools.com/tags/att_input_form.asp
JQuery.ajax and html for validating an "inner form" through ajax, then submitting the entire form. I use ajax in both cases to show the purpose of a controller.php file and a submission id. You could also have an inner form which consists of several segregated sections by using classes instead of ids as Jquery selectors.
<form>
<input />
<textarea />
<select /> <!-- etc. -->
<section id="verify">
<input />
<textarea />
<select /> <!-- etc -->
<button type="button">submit</button>
<!-- eg. sub-submission verifies data in section -->
</section>
<select />
<input />
<input type="submit" value="submit" />
</form>
<script>
$(document).ready(function() {
$("#verify button").on ('click', verify);
$('form').submit (formSend);
function verify (){
// get input data within section only (ie. within inner form)
var postData = $('#verify').filter(':input' ).serializeArray();
postData.push ({name:"submitId", value:'verify'});
var request = $.ajax ({
type: "POST",
url: "controller.php",
data: postData,
error: function (xhr, status, message){
alert (status);
}
});
}
function formSend (){
// get input data within entire form
var postData = $(this).serializeArray();
postData.push ({name:"submitId", value:'send'});
var request = $.ajax ({
type: "POST",
url: "controller.php",
data: postData,
error: function (xhr, status, message){
alert (status);
}
});
}
});
</script>

How do I auto-submit an upload form when a file is selected?

I have a simple file upload form. How do I make it submit automatically when a file has been selected? I don't want the user to have to click the Submit button.
You can simply call your form's submit method in the onchange event of your file input.
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
};
http://jsfiddle.net/cwvc4/73/
Just tell the file-input to automatically submit the form on any change:
<form action="http://example.com">
<input type="file" onchange="form.submit()" />
</form>
This solution works like this:
onchange makes the input element execute the following script, whenever the value is modified
form references the form, that this input element is part of
submit() causes the form to send all data to the URL, as specified in action
Advantages of this solution:
Works without ids. It makes life easier, if you have several forms in one html page.
Native javascript, no jQuery or similar required.
The code is inside the html-tags. If you inspect the html, you will see it's behavior right away.
Using jQuery:
$('#file').change(function() {
$('#target').submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="target" action="destination.html">
<input type="file" id="file" value="Go" />
</form>
JavaScript with onchange event:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="filename" onchange="javascript:this.form.submit();">
</form>
jQuery
.change() and .submit():
$('#fileInput').change(function() {
$('#myForm').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form action="upload.php" id="myForm">
<input type="file" id="fileInput">
</form>
The shortest solution is
<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" />
<form id="thisForm" enctype='multipart/form-data'>
<input type="file" name="file" id="file">
</form>
<script>
$(document).on('ready', function(){
$('#file').on('change', function(){
$('#thisForm').submit();
});
});
</script>
This is my image upload solution, when user selected the file.
HTML part:
<form enctype="multipart/form-data" id="img_form" method="post">
<input id="img_input" type="file" name="image" accept="image/*">
</form>
JavaScript:
document.getElementById('img_input').onchange = function () {
upload();
};
function upload() {
var upload = document.getElementById('img_input');
var image = upload.files[0];
$.ajax({
url:"/foo/bar/uploadPic",
type: "POST",
data: new FormData($('#img_form')[0]),
contentType:false,
cache: false,
processData:false,
success:function (msg) {}
});
};
If you already using jQuery simple:
<input type="file" onChange="$(this).closest('form').submit()"/>
Try bellow code with jquery :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
$('#myForm').on('change', "input#MyFile", function (e) {
e.preventDefault();
$("#myForm").submit();
});
});
</script>
<body>
<div id="content">
<form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
<input type="file" id="MyFile" value="Upload" />
</form>
</div>
</body>
</html>
For those who are using .NET WebForms a full page submit may not be desired. Instead, use the same onchange idea to have javascript click a hidden button (e.g. <asp:Button...) and the hidden button can take of the rest. Make sure you are doing a display: none; on the button and not Visible="false".
HTML
<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>
JAVASCRIPT PURE
<script type="text/javascript">
window.onload = function() {
document.getElementById("xfilename").onchange = function() {
document.getElementById("xtarget").submit();
}
};
</script>
You can put this code to make your code work with just single line of code
<input type="file" onchange="javascript:this.form.submit()">
This will upload the file on server without clicking on submit button
<form action="http://example.com">
<input type="file" onchange="Submit()" />
</form>
<script>
// it will submit form 0 or you have to select particular form
document.getElementsByTagName("form")[0].submit();
</script>
$('#file').change(function() {
$('#target').submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="target" action="destination.html">
<input type="file" id="file" value="Go" />
</form>

Categories