Javascript not working on submit - javascript

In my HTML file, I have the following script:
<script language = "javascript">
function validation(){
var x = document.forms["form"]["fieldx"].value;
var y = document.forms["form"]["fieldy"].value;
var act = document.forms["form"]["action"].value;
if(x == null && y == null && act == "delete"){
var z = confirm("Fields have no input. Proceed at your own risk");
if(z==true) return true;
else return false;
}
}
</script>
And the form:
<form name="form" onsubmit="return validation()" action="cgi-bin/process.cgi" method="GET">
<input type="text" name="fieldx" />
<input type="text" name="fieldy" />
<input type="submit" name="action" value="insert" />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="update" />
</form>
with two input fields named fieldx and fieldy, and a submit type named action which can take any value (i.e. insert, delete and update) as shown above.
Supposedly, when the delete (and only the delete) button is clicked, it will check if there are any inputs inputed on both fields. If there are none, Javascript will prompt and ask the user if it wants to proceed. If he/she clicked yes, well, the process.cgi will be executed and if not, it will just return to the HTML page. However, when I clicked delete, there was no prompt and the cgi was executed.

You have two problems:
First:
x == null && y == null
The values of the fields will never be null. If nothing has been input into them, then their value will be a empty string (i.e. ""). So you need to compare against that and not null.
Second:
document.forms["form"]["action"].value
You have multiple controls named action, so document.forms["form"]["action"] will be a NodeList (which is like an Array). It won't be a single element, and value will always be undefined.
There is no way to tell, from a submit event, which form control was used to activate the form.
Use an onclick handler on the input you care about instead.
<script>
function validation(){
var x = document.forms["form"]["fieldx"].value;
var y = document.forms["form"]["fieldy"].value;
if(x == "" && y == ""){
return confirm("Fields have no input. Proceed at your own risk");
}
}
</script>
and
<input type="submit" name="action" value="delete" onclick="return validation();">
A more modern way to write it would be along these lines:
<form action="cgi-bin/process.cgi">
<input type="text" name="fieldx">
<input type="text" name="fieldy">
<input type="submit" name="action" value="insert" />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="update" />
</form>
<script>
document.querySelector('input[value=delete]').addEventListener('click', validate);
function validate(event) {
var elements = this.form.elements;
if (elements.fieldx.value == "" && elements.fieldy.value == "") {
if (!confirm("Fields have no input. Proceed at your own risk")) {
event.preventDefault();
}
}
}
</script>

Related

How I can POST a Button value in PHP

I have a form in which i use multiple Checkbox. On Checkboxes i use JavaScript for validation If I checked all checkbox, it proceeds ahead otherwise it show an alert message.
My code is working Well
Problem
Because i have Two Button on my form and they have different functionality. I want to post value of Button on my action page
My Code goes here
<script>
function letter_submit(){
var pr = document.getElementsByName('pr'),
i = 0;
var allAreChecked = true;
for( ; i < pr.length; i++ )
{
if( pr[i].checked=='' ) {
allAreChecked = false;
}
}
if (!allAreChecked) {
alert("Please Check All Checkboxes");
exit;
} else {
alert("All OK");
document.getElementById("approve_letter").submit();
}
}
</script>
<form action="letter_approve_action.php" id="approve_letter" name = "approve_letter" method="POST" >
<input type="checkbox" name="pr" id="pr" value="" /> NL is appropriately addressed.
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Checked Press Release
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Applicable Methodology is rightly Marked
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Respective Sector Study on Website is Updated Within Last 12 Months.
</br>
<button type="button" name="btn_submit" id="btn_submit" value="Approve" onclick="letter_submit();">Approve</button>
<button type="button" name="btn_submit" id="btn_submit" value="Re - Submit" />Re-Submit</button>
</form>
On action page i use
echo $submit = $_POST ['btn_submit'];
and i got an error
Notice: Undefined index: btn_submit in C:\xampp\htdocs\Work_Que_Backup\login\pacra-all\w_q\nl\letter_approve_action.php on line 26
You may use <button> tag.
For example:
<form method="post">
<input type="text" name="myText" value="some text here..."/>
<button type="submit" name="myButton" value="buttonValue">Submit</button>
</form>
The label tht is displayed is "Submit" but you can access your button value from the server with a different value.
It will be accessible with php on server side as:
echo $_POST['myButton']; //buttonValue
The problem in your code is that your button is of type "button", and you trigger the POST by javascript - so the value for btn_submit is never set.
Change the button type to "submit" and move the event handler onclick=... to the form tag onsubmit=.... In your javascript function, you can the cancel the submit by returning false.

PHP Form Submits Before Javascript Validation

I'm having a somewhat common problem of getting my form to validate before submission. I've tried several variations on the same theme and with no dice: at best I could get nothing to submit, but usually my form just ignores codes and submits anyway.
Chances are I'm missing something small but I'd appreciate any help! Essentially just trying to make sure the name isn't empty here (return true; is pointless IIRC but I was getting desperate haha). Once I can get some basic level of validation down it just comes down to coding the JS for more complicated maneuvers so this should be good enough, i hope. Thanks!
<script>
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else {
return true;
}
alert("Bla");
}
</script>
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm(); return false;"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
You're making it to complex.
JavaScript:
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else { return true; }
}
HTML:
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm()"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
Your validation works fine, but because you are trying to
document.getElementByID("JSError").innerHTML
instead of
document.getElementById("JSError").innerHTML
JS throws an error and never reaches your "return false".
You can easily see this, when you use your browsers console output. (In firefox and chrome press F12).
Example fiddle: http://jsfiddle.net/6tFcw/
1st solution - using input[type=submit]
<!-- HTML -->
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
// JavaScript
function validateForm(){
var target = document.getElementById("name"); // for instance
if(target.value.length === 0){
alert("Name is required");
return false;
}
// all right; submit the form
return true;
}
2nd solution - using input[type=button]
<!-- html -->
<input type="button" name="submit" id="submit" value="Submit" />
// JavaScript
window.onload = function(){
var target = document.getElementById("name");
document.getElementById("submit").onclick = function(){
if(target.value.length === 0){
alert("Name is required");
}else{
// all right; submit the form
form.submit();
}
};
};

Simple JavaScript Checkbox Validation

I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.
Here is my form:
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="----??----" />
The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.
Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.
You could use:
if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
(demo page).
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
! is the Boolean NOT operator.
this is the submit button because it is the element the event handler is attached to.
.form is the form the submit button is in.
.checkbox is the control named "checkbox" in that form.
.checked is true if the checkbox is checked and false if the checkbox is unchecked.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept SOMETHING Terms and Conditions</p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
You can do the following:
<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
<input type="checkbox" name="checkbox" value="check" id="agree" />
<input type="submit" name="email_submit" value="submit" />
</form>​
Here is a working demo - http://jsfiddle.net/Ccr2x/
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.
HTML:
<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />
JavaScript:
var alterDisabledState = function () {
var isMyCheckboxChecked = $('#myCheckbox').is(':checked');
if (isMyCheckboxChecked) {
$('myButton').removeAttr("disabled");
}
else {
$('myButton').attr("disabled", "disabled");
}
}
Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.
Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked.
By using checked property we check whether the checkbox is selected or not.
cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"
You can do the following:
function validate() {
var cbox = document.forms["myForm"]["gender"];
if (
cbox[0].checked == false &&
cbox[1].checked == false &&
cbox[2].checked == false
) {
alert("Please Select Gender");
return false;
} else {
alert("Successfully Submited");
return true;
}
}
<form onload="return validate()" name="myForm">
<input type="checkbox" name="gender" value="male"> Male
<input type="checkbox" name="gender" value="female"> Female
<input type="checkbox" name="gender" value="other"> Other <br>
<input type="submit" name="submit" value="Submit" onclick="validate()">
</form>
Demo: CodePen
Target it by id and then use this code:
function check(){
if(document.getElementById('yourid').checked
{
return false;
}
else
{
alert ("checkbox not checked");
return false;
}
}
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
Guys you can do this kind of validation very easily. Just you have to track the id or name of the checkboxes. you can do it statically or dynamically.
For statically you can use hard coded id of the checkboxes and for dynamically you can use the name of the field as an array and create a loop.
Please check the below link. You will get my point very easily.
http://expertsdiscussion.com/checkbox-validation-using-javascript-t29.html
Thanks

How To Determine Which Submit Button Was Pressed, Form onSubmit Event, Without jQuery [duplicate]

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
}

Can I determine which Submit button was used in javascript?

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);
}
});

Categories