I have the form with action targeted for the specified task. I want to have this form also sent by email. It can be the :mailto option or other.
Mailto on submit button
So When I click the Submit form, the form is submitted. However I would like to attach another action to this action, namely I would like to send this filled form to the email by checking the ckeckbox.
So far I saw, that sending the form by checkbox is possible:
submitting a form when a checkbox is checked
but the pivot thing here is assigning the other form action to my form...
HTML form with multiple "actions"
I tried something like this:
<form id="c_form" action="default_url_when_press_enter" method="get" onsubmit="return validate(this);" target="_blank" >
....
<input type="checkbox" action="mailto:mk#gmail.com" id="cfemail" name="email">
<input class="btn" action="c_form.html" type="submit" id="cfsubmit" value="Submit form">
but it didn't work unfortunately as well as with the code applied below:
document.getElementById("cfsubmit").addEventListener("click", function(){
document.getElementById("c_form").className="submitted";
});
How can I send email along with the form submission when my box is checked?
The full code is available here:
https://jsfiddle.net/ptgbvfen/
So far if I understand your problem correctly, you want to submit the form normally. But if the checkbox is checked you want to perform a mailto function as well.
HTML:
<form id="c_form" onsubmit="return validate(this);" target="_self" >
....
<input type="checkbox" id="openmail" name="email">
<input class="btn" type="button" id="cfsubmit" value="Submit form">
Javascript
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("opemail"); // Get checkbox element
var mainForm = document.getElementById("c_form"); // Get form element
if (check.checked == true) { // If checked then fire
let link=document.createElement("a"); // Creates <a> element in DOM
link.href = "mailto:mk#gmail.com"; // Adds mailto link to <a>
link.click(); // Clicks the <a> and open default mail app
link.remove();
}
mainForm.submit(); // Submits the form
});
Updated___
Removed the action attribute from form element, because you do not need it when you want the form to submit on the current page. Also changed the target attribute to _self so that it will not open new tab whenever you submit the form.
Updated V2_
Made mailto autofill the email content when checkbox checked and form is submitted, as requested. If you find it helpful then kindly upvote, and if you are facing more issue then comment down below. Thanks.
Demo: https://jsfiddle.net/rzos1bwt/
HTML
<form id="c_form" onsubmit="return false;">
<div id="Page1">
<h2 class="property">Property information</h2>
<fieldset>
<figure class="property_information">
<figure class="fig">
<label>
<div class="order">A</div>
<p>Proposed Cable Route<span class="asterisk">*</span></p>
</label>
<br>
<select name="proposed_cable_route" id="cf_proposed_cable_route">
<option value="" disabled selected>-Select your answer-</option>
<option value="External">External</option>
<option value="Internal">Internal</option>
<option value="Combination">PIA</option>
</select>
</figure>
<figure class="fig" id="cf_building_post_2000">
<label>
<div class="order">B</div>
<p>Is the building post 2000?
<span class="asterisk">*</span>
</p>
</label>
<br>
<input name="building_post_2000" type="radio" value="Yes" selected>Yes
<input name="building_post_2000" type="radio" value="No">No
<br>
</figure>
<figure class="fig" id="cfasbestos">
<label>
<div class="order">C</div>
<p>Do you have asbestos report?
<span class="asterisk">*</span>
</p>
</label>
<br>
<input name="asbestos_report" type="radio" value="Yes" selected>Yes
<input name="asbestos_report" type="radio" value="No">No
<br>
<h3 class="alert">Please contact your team leader for advice!</h3>
</figure>
</figure>
<figure class="fig">
<label>
<div class="order">9</div>
<p>Surveyor<span class="asterisk">*</span></p>
</label>
<br>
<input type="text" name="surveyor" placeholder="Surveyor's name">
<input type="email" name="surveyor_email" placeholder="Email">
<br>
</figure>
<div class="emailreceipt">
<input type="checkbox" id="opemail" name="email">
<label for="opemail">Send me an email receipt of my responses</label>
</div>
<input class="btn" type="submit" id="cfsubmit" value="Submit form">
</fieldset>
</div>
</form>
Javascript
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("opemail"); // Get checkbox element
var formEl = document.forms.c_form; // Get the form
var formData = new FormData(formEl); // Creates form object
// Get all form data values
var cableRoute = formData.get('proposed_cable_route');
var buildingPost = formData.get('building_post_2000');
var asbestosReport = formData.get('asbestos_report');
var surveyorName = formData.get('surveyor');
var surveyorEmail = formData.get('surveyor_email');
// This will create the subject of form
var subject = "Submission from " + surveyorName;
// This will create body with filled data
var body = 'My name is ' + surveyorName + '\n' + 'My email is ' + surveyorEmail + '\n' + 'Proposed Cable Route: ' + cableRoute + '\n' + 'Is the building post 2000: ' + buildingPost + '\n' + 'Do you have asbestos report: ' + asbestosReport;
// Making the mailto link with urlencoding
var mailTo = "mailto:mk#gmail.com?subject="+encodeURI(subject)+"&body="+encodeURI(body);
if (check.checked == true) { // If checked then fire
let link=document.createElement("a"); // Creates <a> element in DOM
link.href = mailTo; // Adds mailto link to <a>
link.click(); // Clicks the <a> and open default mail app
link.remove();
}
//console.log("mailTo => ", mailTo)
mainForm.submit(); // Submits the form
});
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">
<form action="formoneaction" method="post">
<input type="text" id="t1" />
<button type="sumbit" class="btn">Insert</button>
</form>
<form action="formtwoaction" method="post">
<input type="text" id="t2" />
<button type="sumbit" class="btn">Insert</button>
</form>
<script>
var t1 = document.getElementById('t1');
t1.onkeyup = t1.onchange = function() {
document.getElementById('t2').value = this.value;
};
</script>
How can I get the script to work when the two elements are in separate forms? The script works when none of them are in forms.
I've never learned JS before so I may not understand very well when someone explains a bunch of jargon. Sorry but I'll try my best!
Try out below Code, which copies data from textbox to TextArea:
$("#textArea").append("\n * " + $("#textBox").val());
Working Demo
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();
});
});
I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form