I have a very simple form with a name field and two submit buttons: 'change' and 'delete'. I need to do some form validation in javascript when the form is submitted so I need to know which button was clicked. If the user hits the enter key, the 'change' value is the one that makes it to the server. So really, I just need to know if the 'delete' button was clicked or not.
Can I determine which button was clicked? Or do I need to change the 'delete' button from a submit to a regular button and catch its onclick event to submit the form?
The form looks like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
In the checkForm() function, form["submit"] is a node list, not a single element I can grab the value of.
Here's an unobtrusive approach using jQuery...
$(function ()
{
// for each form on the page...
$("form").each(function ()
{
var that = $(this); // define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit", that).bind("click keypress", function ()
{
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
// assign submit-event to all forms on the page
$("form").submit(function ()
{
/* retrieve the id of the input that was clicked, stored on
it's enclosing form */
var callerId = $(this).data("callerid");
// determine appropriate action(s)
if (callerId == "delete") // do stuff...
if (callerId == "change") // do stuff...
/* note: you can return false to prevent the default behavior
of the form--that is; stop the page from submitting */
});
});
Note: this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.
You could also use the onclick event in a number of different ways to address the problem.
For instance:
<input type="submit" name="submit" value="Delete"
onclick="return TryingToDelete();" />
In the TryingToDelete() function in JavaScript, do what you want, then return false if do not want the delete to proceed.
Some browsers (at least Firefox, Opera and IE) support this:
<script type="text/javascript">
function checkForm(form, event) {
// Firefox || Opera || IE || unsupported
var target = event.explicitOriginalTarget || event.relatedTarget ||
document.activeElement || {};
alert(target.type + ' ' + target.value);
return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
For an inherently cross-browser solution, you'll have to add onclick handlers to the buttons themselves.
<html>
<script type="text/javascript">
var submit;
function checkForm(form)
{
alert(submit.value);
return false;
}
function Clicked(button)
{
submit= button ;
}
</script>
<body>
<form method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Change" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Delete" />
</form>
</body>
</html>
You could use the SubmitEvent.submitter property.
form.addEventListener('submit', event => console.log(event.submitter))
Give each of the buttons a unique ID such as
<input type="submit" id="submitButton" name="submit" value="Change" />
<input type="submit" id="deleteButton" name="submit" value="Delete" />
I'm not sure how to do this in raw javascript but in jquery you can then do
$('#submitButton').click(function() {
//do something
});
$('#deleteButton').click(function() {
//do something
});
This says that if submitButton is clicked, do whatever is inside it.
if deleteButton is clicked, do whatever is inside it
In jQuery you can use $.data() to keep data in scope - no need for global variables in that case.
First you click submit button, then (depending on it's action) you assign data to form. I'm not preventing default action in click event, so form is submitted right after click event ends.
HTML:
<form action="update.php" method="post"">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
JavaScript:
(function ($) {
"use strict";
$(document).ready(function () {
// click on submit button with action "Change"
$('input[value="Change"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Change");
});
// click on submit button with action "Delete"
$('input[value="Delete"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Delete");
});
// on form submit
$('form').on("submit", function () {
var $self = $(this);
// retrieve action type from form
// If there is none assigned, go for the default one
var action = $self.data("action") || "deafult";
// remove data so next time you won't trigger wrong action
$self.removeData("action");
// do sth depending on action type
if (action === "change") {
}
});
});
})(jQuery);
Right now you've got the same problem as you would a normal text input. You've got the same name on two different elements. Change the names to "Change" and "Delete" and then determine if either one of them were clicked by applying an event handler on both submits and providing different methods. I'm assuming you're using pure JavaScript, but if you want it to be quick, take a look at jQuery.
What you need is as simple as following what's on w3schools
Since you didn't mention using any framework, this is the cleanest way to do it with straight Javascript. With this code what you're doing is passing the button object itself into the go() function. You then have access to all of the button's properties. You don't have to do anything with setTimeout(0) or any other wacky functions.
<script type="text/javascript">
function go(button) {
if (button.id = 'submit1')
//do something
else if (button.id = 'submit2')
//do something else
}
</script>
<form action="update.php" method="post">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input id="submit1" type="submit" name="submit" value="Change" onclick="go(this);"/>
<input id="submit2" type="submit" name="submit" value="Delete" onclick="go(this);"/>
</form>
A click event anywhere in a form will be caught by a form's click handler (as long as the element clicked on allows it to propagate). It will be processed before the form's submit event.
Therefore, one can test whether the click target was an input (or button) tag of the submit type, and save the value of it (say, to a data-button attribute on the form) for processing in the form's submit handler.
The submit buttons themselves do not then need any event handlers.
I needed to do this to change a form's action and target attributes, depending upon which submit button is clicked.
// TO CAPTURE THE BUTTON CLICKED
function get_button(){
var oElement=event.target;
var oForm=oElement.form;
// IF SUBMIT INPUT BUTTON (CHANGE 'INPUT' TO 'BUTTON' IF USING THAT TAG)
if((oElement.tagName=='INPUT')&&(oElement.type=='submit')){
// SAVE THE ACTION
oForm.setAttribute('data-button',oElement.value);
}
}
// TO DO THE SUBMIT PROCESSING
function submit_form(){
var oForm=event.target;
// RETRIEVE THE BUTTON CLICKED, IF ONE WAS USED
var sAction='';
if(oForm.hasAttribute('data-button')){
// SAVE THE BUTTON, THEN DELETE THE ATTRIBUTE (SO NOT USED ON ANOTHER SUBMIT)
sAction=oForm.getAttribute('data-button');
oForm.removeAttribute('data-button');
}
// PROCESS BY THE BUTTON USED
switch(sAction){
case'Change':
// WHATEVER
alert('Change');
break;
case'Delete':
// WHATEVER
alert('Delete');
break;
default:
// WHATEVER FOR ENTER PRESSED
alert('submit: By other means');
break;
}
}
<form action="update.php" method="post" onsubmit="submit_form();" onclick="get_button();">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
<p id="result"></p>
Here is my solution:
Just add dataset in submit button like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" data-clicked="change" />
<input type="submit" name="submit" value="Delete" data-clicked="delete" />
</form>
In JS access it by:
$('body').on("submit", function(event){
var target = event.explicitOriginalTarget || event.relatedTarget || document.activeElement || {};
var buttonClicked = target.dataset['clicked'];
console.log(buttonClicked);
});
Name the delete button something else. Perhaps name one SubmitChange and name the other SubmitDelete.
I've been dealing with this problem myself. There's no built-in way to tell which button's submitting a form, but it's a feature which might show up in the future.
The workaround I use in production is to store the button somewhere for one event loop on click. The JavaScript could look something like this:
function grabSubmitter(input){
input.form.submitter = input;
setTimeout(function(){
input.form.submitter = null;
}, 0);
}
... and you'd set an onclick on each button:
<input type="submit" name="name" value="value" onclick="grabSubmitter(this)">
click fires before submit, so in your submit event, if there's a submitter on your form, a button was clicked.
I'm using jQuery, so I use $.fn.data() instead of expando to store the submitter. I have a tiny plugin to handle temporarily setting data on an element that looks like this:
$.fn.briefData = function(key, value){
var $el = this;
$el.data(key, value);
setTimeout(function(){
$el.removeData(key);
}, 0);
};
and I attach it to buttons like this:
$(':button, :submit').live('click', function () {
var $form = $(this.form);
if ($form.length) {
$form.briefData('submitter', this);
}
});
Related
I have three forms on a page with submit buttons in each, there is a code which is suppose to changes the value of a button in a particular form when clicked but when i click on that submit button all the values in the various forms buttons changes, but i want to change the value based on the form i click
<script language="javascript">
/**
* Disable submit button
*/
$(function(){
$('input:submit').click(function(){
$(this).val('Request Placed...');
$(this).attr('disabled', 'disabled');
$(this).parents('form').submit();
});
});
$(window).load(function(){
$('input:submit').removeAttr('disabled');
});
</script>
Use jQuery selector to select only form that you need, only input from form with id="form_2" will be supported
$(function(){
$('input:submit', '#form_2').click(function(){
$(this).val('Request Placed...');
$(this).attr('disabled', 'disabled');
});
});
jsfiddle: http://jsfiddle.net/krzysztof_safjanowski/sP2Zv/2/
I am not sure about your requirements. However, this demo might give you some ideas to resolve your issues.
HTML:
<form id="form1" action="action1">
<input type="text" id="txt1" />
<input type="submit" value="Submit" />
</form>
<form id="form2" action="action2">
<input type="text" id="txt2" />
<input type="submit" value="Submit" />
</form>
<form id="form3" action="action3">
<input type="text" id="txt3" />
<input type="submit" value="Submit" />
</form>
JavaScript:
(function () {
var $submitBtn,
$form,
submitBtnHandler = function (event) {
event.preventDefault();
var $self = $(this);
$self.val('Request Placed...');
$self.prop('disabled', true);
$self.parents('form').submit();
},
formSubmitHandler = function (event) {
event.preventDefault(); // Added this to stay in the same page when submit form. If you want to redirect to the action URL(action1, action2, action3 etc), please remove it.
alert("Hi, I am " + this.id);
},
resetSubmitBtnState = function () {
$submitBtn.removeAttr('disabled');
},
init = function () {
$submitBtn = $('input:submit');
$form = $('form');
$submitBtn.on('click', submitBtnHandler);
$form.on('submit', formSubmitHandler);
};
$(document).ready(init);
$(window).load(resetSubmitBtnState);
}());
JSFiddle Demo: http://jsfiddle.net/w3devjs/3Byb2/
In JavaScript you could do this,
document.getElementById("BUTTON'S ID").value = "TEXT HERE";
Just make that line an onclick one.
So, when the user clicks the button, an onclick event happens, that will change the button's vaule. Be sure that in the input tag, there is an id for the button as well as a value for it.
So, here's a little example I whipped up,
In HTML,
<form>
<input type="text" id="Input" />
<input type="button" id="BUTTON'S ID" value="TEXT HERE" onclick="Changetxt()" />
</form>
In JavaScript,
<script>
function Changetxt()
{
document.getElementById("BUTTON'S ID").value = "SOME OTHER TEXT";
}
</script>
So, when the user clicks the button, the button's text changes from TEXT HERE to SOME OTHER TEXT.
how can i get a specific element of a text input into a variable via javascript, in other words take the example below
<form id="123">
<input type="text" id="supply_qty" />
<input type="submit" name="submit" id="123" />
</form>
How do i get the element within the text input into a variable when the submit button is clicked, the problem i have is that i have multiple instances of the code above, with lots of text inputs, so i only want to get the element specific to the submit button clicked. Hopefully you will get what i mean. The reason i need this done via JavaScript and not php etc... is that i later want to use ajax with it, but for the moment i just need the variable.
Thanks
The most easiest way is to give and id to the element and user getElementById() method to grab the element on variable. Just like what you are doing right now
Simple Example:
var button = document.getElementyById("123");
button.onclick = function() {
var text = document.getElementById('supply_qty'); //now you got your element in varaiblle
};
Using jQuery make a slight change to your markup. I am just going to add some classes.
<form>
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
then
$(".submit").click(function() {
var txtbox = $(this).parent("form").children(".textbox")[0];
});
Or, it might be better to bind to the submit handler of the form, on that case, give a common class to the form.
<form class="tinyforms">
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
Then
$('.tinyforms').submit(function() {
var txtbox = $(this).children(".textbox")[0];
});
If you accept using jQuery you can do this:
DOM
<form class="form" action="false">
<input type="text" value="some input" name="textInput" />
<input type="text" value="some text" name="textInput2" />
<input type="submit" class="sumbit" value="Send" />
<div id="results"></div>
</form>
And JavaScript
$(".form").submit( function(){
var inputs = $(this).serializeArray();
$.each(inputs , function(i, input){
$("#results").append(input.value + "<br />");
});
return false;
} );
EDIT: Updated code and Fiddle: http://jsfiddle.net/65Xtp/4/
I am trying to disable a button on click, as well as change the text of the button. here is my code:
<input type="submit" value="Register" name="submit" id="submit" onClick="javascript:replaceButtonText('submit', 'Please wait...'); document.form1.submit.disabled=true;">
What is happening, is the button gets disabled, and the text changes, but the form does not do anything (submit). what am I doing wrong?
This works:
<html>
<body>
<form name="form1" method="post" action="myaction">
<input type="text" value="text1"/>
<input type="submit" value="Register" name="submit" id="submit"
onclick="javascript: replaceButtonText('submit1', 'Please wait...'); document.form1.submit.disabled=true; return true; ">
</form>
</body>
</html>
Form controls with a name are made available as named properties of the form they are in using their name. So:
document.form1.submit
refers to the button, not the submit method.
Writing:
< ... onclick="javascript:..." ...>
means that "javascript" is treated as a useless label, just don't do it. If you want the button to become disabled and change its label when the form is submitted, then use something like:
<form>
<input name=foo value=bar>
<input type="submit" onclick="
this.value='Please wait...';
this.disabled = true;
var theForm = this.form;
window.setTimeout(function(){theForm.submit();},1);
">
</form>
and let the form submit normally.
Of course the function in the onclick attribute should be a function call rather than a slab of code, but you get the idea.
This question already has answers here:
How can I get the button that caused the submit from the form submit event?
(22 answers)
Determine which element triggered a form submit event
(3 answers)
Closed 9 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a form with two submit buttons and some code:
HTML:
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
JavaScript:
form.onSubmit = function(evnt) {
// Do some asynchronous stuff, that will later on submit the form
return false;
}
Of course the two submit buttons accomplish different things. Is there a way to find out in onSubmit which button was pressed, so later I could submit by doing thatButton.click()?
Ideally I would like to not modify the code for the buttons, just have a pure JavaScript addon that has this behavior.
I know that Firefox has evnt.explicitOriginalTarget, but I can't find anything for other browsers.
<form onsubmit="alert(this.submitted); return false;">
<input onclick="this.form.submitted=this.value;" type="submit" value="Yes" />
<input onclick="this.form.submitted=this.value;" type="submit" value="No" />
</form>
jsfiddle for the same
Not in the submit event handler itself, no.
But what you can do is add click handlers to each submit which will inform the submit handler as to which was clicked.
Here's a full example (using jQuery for brevity)
<html>
<head>
<title>Test Page</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(function($) {
var submitActor = null;
var $form = $('#test');
var $submitActors = $form.find('input[type=submit]');
$form.submit(function(event) {
if (null === submitActor) {
// If no actor is explicitly clicked, the browser will
// automatically choose the first in source-order
// so we do the same here
submitActor = $submitActors[0];
}
console.log(submitActor.name);
// alert(submitActor.name);
return false;
});
$submitActors.click(function(event) {
submitActor = this;
});
});
</script>
</head>
<body>
<form id="test">
<input type="text" />
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
</form>
</body>
</html>
Bare bones, but confirmed working, example:
<script type="text/javascript">
var clicked;
function mysubmit() {
alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
<input type="submit" onclick="clicked='Save'" value="Save" />
<input type="submit" onclick="clicked='Add'" value="Add" />
</form>
All of the answers above are very good but I cleaned it up a little bit.
This solution automatically puts the name of the submit button pressed into the action hidden field. Both the javascript on the page and the server code can check the action hidden field value as needed.
The solution uses jquery to automatically apply to all submit buttons.
<input type="hidden" name="action" id="action" />
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//when a submit button is clicked, put its name into the action hidden field
$(":submit").click(function () { $("#action").val(this.name); });
});
</script>
<input type="submit" class="bttn" value="<< Back" name="back" />
<input type="submit" class="bttn" value="Finish" name="finish" />
<input type="submit" class="bttn" value="Save" name="save" />
<input type="submit" class="bttn" value="Next >>" name="next" />
<input type="submit" class="bttn" value="Delete" name="delete" />
<input type="button" class="bttn" name="cancel" value="Cancel" onclick="window.close();" />
Then write code like this into your form submit handler.
if ($("#action").val() == "delete") {
return confirm("Are you sure you want to delete the selected item?");
}
First Suggestion:
Create a Javascript Variable that will reference the button clicked. Lets call it buttonIndex
<input type="submit" onclick="buttonIndex=0;" name="save" value="Save" />
<input type="submit" onclick="buttonIndex=1;" name="saveAndAdd" value="Save and add another" />
Now, you can access that value. 0 means the save button was clicked, 1 means the saveAndAdd Button was clicked.
Second Suggestion
The way I would handle this is to create two JS functions that handle each of the two buttons.
First, make sure your form has a valid ID. For this example, I'll say the ID is "myForm"
change
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
to
<input type="submit" onclick="submitFunc();return(false);" name="save" value="Save" />
<input type="submit" onclick="submitAndAddFunc();return(false);" name="saveAndAdd" value="Save and add
the return(false) will prevent your form submission from actually processing, and call your custom functions, where you can submit the form later on.
Then your functions will work something like this...
function submitFunc(){
// Do some asyncrhnous stuff, that will later on submit the form
if (okToSubmit) {
document.getElementById('myForm').submit();
}
}
function submitAndAddFunc(){
// Do some asyncrhnous stuff, that will later on submit the form
if (okToSubmit) {
document.getElementById('myForm').submit();
}
}
OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.
<script language="javascript" type="text/javascript">
var initiator = '';
$(document).ready(function() {
$(":submit").click(function() { initiator = this.name });
});
</script>
Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.
~Spanky
I use Ext, so I ended up doing this:
var theForm = Ext.get("theform");
var inputButtons = Ext.DomQuery.jsSelect('input[type="submit"]', theForm.dom);
var inputButtonPressed = null;
for (var i = 0; i < inputButtons.length; i++) {
Ext.fly(inputButtons[i]).on('click', function() {
inputButtonPressed = this;
}, inputButtons[i]);
}
and then when it was time submit I did
if (inputButtonPressed !== null) inputButtonPressed.click();
else theForm.dom.submit();
Wait, you say. This will loop if you're not careful. So, onSubmit must sometimes return true
// Notice I'm not using Ext here, because they can't stop the submit
theForm.dom.onsubmit = function () {
if (gottaDoSomething) {
// Do something asynchronous, call the two lines above when done.
gottaDoSomething = false;
return false;
}
return true;
}
Why not loop through the inputs and then add onclick handlers to each?
You don't have to do this in HTML, but you can add a handler to each button like:
button.onclick = function(){ DoStuff(this.value); return false; } // return false; so that form does not submit
Then your function could "do stuff" according to whichever value you passed:
function DoStuff(val) {
if( val === "Val 1" ) {
// Do some stuff
}
// Do other stuff
}
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