How to catch a form submit action in JavaScript/jQuery? - javascript

I have a form that the user can submit using the two following buttons:
<input type="submit" name="delete" value="delete" id="deletebutton" class="pure-button">
<input type='submit' id="submitbutton" name="btnSubmit" value="save" class="pure-button pure-button-primary">
I have an submit event listener that loads a certain function I need to process the form (the form has id #submitform):
document.querySelector('#submitform').addEventListener('submit', function(e) {
e.preventDefault();
// Some code goes here
});
However, this code only reacts when #submitbutton is clicked. When #deletebutton is clicked the form submits as usual.
How do I avoid that and have another function listening to whether #deletebutton is clicked?
Thank you!

Why dont you simply try like below
$("#submitform").submit(function(event){
var isValid = true;
// do all your validation if need here
if (!isValid) {
event.preventDefault();
}
});
Make sure both the buttons inside the form closing tag
and your event listener was not properly closed
document.querySelector('#submitform').addEventListener('submit', function(e) {
e.preventDefault();
// Some code goes here
});

I would add another listenter for the delete button.
document.querySelector('#deletebutton').addEventListener('submit', function(e) {
e.preventDefault();
// Some code goes here
// commonFunct() { ... }
}
If both buttons will perform common code/action you can call a common function so you don't have to repeat yourself.

Related

Confirm dialog posting on Cancel button?

I'm using the following <a> tag to display a simple confirm which it does. However, when I click the Cancel button it still performs the post method. From my understanding, having the return in front of confirm should cause the form to not post if the Cancel button is clicked.
<a href="#"
data-potr-action="delete"
data-potr-val="#item.RID"
onclick="return confirm('Are you sure you want to delete this Request?');"
class="btn btn-default btn-sm">
<i class="glyphicon glyphicon-trash"></i> Delete
</a>
I have this code at the end of the page but I don't think it has anything to do with the issue. I didn't thinking it would fire the click event when selecting Cancel in the Confirm dialog.
This just takes the values in the data-action and data-value and stores them to a hidden field. This is done on click which it shouldn't be getting to.
#section scripts {
<script>
$(document).ready(function () {
// Hook events on buttons and anchors
buildClickEvents();
});
// Hook events on buttons and anchors
function buildClickEvents() {
$("[data-potr-action]").on("click", function (e) {
e.preventDefault();
$("#EventCommand").val(
$(this).data("potr-action"));
$("#EventArgument").val(
$(this).attr("data-potr-val"));
$("form").submit();
});
}
</script>
}
To answer your question no confirm doesn't block form post. It return true if pressed "OK" or false if pressed "Cancel" button. See this from W3c
What you could is as below:
function buildClickEvents() {
$("[data-potr-action]").on("click", function (e) {
e.preventDefault();
var result = confirm('Are you sure you want to delete this Request?');
if(result == false){
return;
}
$("#EventCommand").val(
$(this).data("potr-action"));
$("#EventArgument").val(
$(this).attr("data-potr-val"));
$("form").submit();
});
}
And remove the below from a tag:
onclick="return confirm('Are you sure you want to delete this Request?');"
$("[data-potr-action]").on("click", function (e) {
if(confirm("your message")){
$("#EventCommand").val(
$(this).data("potr-action"));
$("#EventArgument").val(
$(this).attr("data-potr-val"));
$("form").submit();
}
e.preventDefault();
});

How to disable submit button? [duplicate]

I wrote this code to disable submit buttons on my website after the click:
$('input[type=submit]').click(function(){
$(this).attr('disabled', 'disabled');
});
Unfortunately, it doesn't send the form. How can I fix this?
EDIT
I'd like to bind the submit, not the form :)
Do it onSubmit():
$('form#id').submit(function(){
$(this).find(':input[type=submit]').prop('disabled', true);
});
What is happening is you're disabling the button altogether before it actually triggers the submit event.
You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.
Demonstration: http://jsfiddle.net/userdude/2hgnZ/
(Note, I use preventDefault() and return false so the form doesn't actual submit in the example; leave this off in your use.)
Specifically if someone is facing problem in Chrome:
What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...
<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;">
<input type="submit" name="submit" value="Submit" id="submit">
</form>
Disabled controls do not submit their values which does not help in knowing if the user clicked save or delete.
So I store the button value in a hidden which does get submitted. The name of the hidden is the same as the button name. I call all my buttons by the name of button.
E.g. <button type="submit" name="button" value="save">Save</button>
Based on this I found here. Just store the clicked button in a variable.
$(document).ready(function(){
var submitButton$;
$(document).on('click', ":submit", function (e)
{
// you may choose to remove disabled from all buttons first here.
submitButton$ = $(this);
});
$(document).on('submit', "form", function(e)
{
var form$ = $(this);
var hiddenButton$ = $('#button', form$);
if (IsNull(hiddenButton$))
{
// add the hidden to the form as needed
hiddenButton$ = $('<input>')
.attr({ type: 'hidden', id: 'button', name: 'button' })
.appendTo(form$);
}
hiddenButton$.attr('value', submitButton$.attr('value'));
submitButton$.attr("disabled", "disabled");
}
});
Here is my IsNull function. Use or substitue your own version for IsNull or undefined etc.
function IsNull(obj)
{
var is;
if (obj instanceof jQuery)
is = obj.length <= 0;
else
is = obj === null || typeof obj === 'undefined' || obj == "";
return is;
}
Simple and effective solution is
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
Source: here
This should take care of it in your app.
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
A more simplier way.
I've tried this and it worked fine for me:
$(':input[type=submit]').prop('disabled', true);
Want to submit value of button as well and prevent double form submit?
If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});
Your code actually works on FF, it doesn't work on Chrome.
This works on FF and Chrome.
$(document).ready(function() {
// Solution for disabling the submit temporarily for all the submit buttons.
// Avoids double form submit.
// Doing it directly on the submit click made the form not to submit in Chrome.
// This works in FF and Chrome.
$('form').on('submit', function(e){
//console.log('submit2', e, $(this).find('[clicked=true]'));
var submit = $(this).find('[clicked=true]')[0];
if (!submit.hasAttribute('disabled'))
{
submit.setAttribute('disabled', true);
setTimeout(function(){
submit.removeAttribute('disabled');
}, 1000);
}
submit.removeAttribute('clicked');
e.preventDefault();
});
$('[type=submit]').on('click touchstart', function(){
this.setAttribute('clicked', true);
});
});
</script>
How to disable submit button
just call a function on onclick event and... return true to submit and false to disable submit.
OR
call a function on window.onload like :
window.onload = init();
and in init() do something like this :
var theForm = document.getElementById(‘theForm’);
theForm.onsubmit = // what ever you want to do
The following worked for me:
var form_enabled = true;
$().ready(function(){
// allow the user to submit the form only once each time the page loads
$('#form_id').on('submit', function(){
if (form_enabled) {
form_enabled = false;
return true;
}
return false;
});
});
This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)
I have been using blockUI to avoid browser incompatibilies on disabled or hidden buttons.
http://malsup.com/jquery/block/#element
Then my buttons have a class autobutton:
$(".autobutton").click(
function(event) {
var nv = $(this).html();
var nv2 = '<span class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></span> ' + nv;
$(this).html(nv2);
var form = $(this).parents('form:first');
$(this).block({ message: null });
form.submit();
});
Then a form is like that:
<form>
....
<button class="autobutton">Submit</button>
</form>
Button Code
<button id="submit" name="submit" type="submit" value="Submit">Submit</button>
Disable Button
if(When You Disable the button this Case){
$(':input[type="submit"]').prop('disabled', true);
}else{
$(':input[type="submit"]').prop('disabled', false);
}
Note: You Case may Be Multiple this time more condition may need
Easy Method:
Javascript & HTML:
$('form#id').submit(function(e){
$(this).children('input[type=submit]').attr('disabled', 'disabled');
// this is just for demonstration
e.preventDefault();
return false;
});
<!-- begin snippet: js hide: false console: true babel: false -->
<form id="id">
<input type="submit"/>
</form>
Note: works perfectly on chrome and edge.
The simplest pure javascript solution is to simply disable the button:
<form id="blah" action="foo.php" method="post" onSubmit="return checkForm();">
<button id="blahButton">Submit</button>
</form>
document.getElementById('blahButton').disabled = true ;
It works with/without onSubmit. Form stays visible, but nothing can be sumbitted.
In my case i had to put a little delay so that form submits correctly and then disable the button
$(document).on('submit','#for',function()
{
var $this = $(this);
setTimeout(function (){
$this.find(':input[type=submit]').attr('disabled', 'disabled')
},1);
});

Submit form with two submit buttons, each performing different actions issue

I have a JSP page, which has standard form on it. I have two buttons, each perform a different action when pressed, and the form is submitted - action 1 and action 2.
I originally had this set up for one button, so it was all done through the following and worked fine:
$('#form').submit( function() { .... }
But now I have two buttons, I want it to do the same, but how to find which button I pressed.
I could do this through the .click function, but I dont want to break my existing form.submit functionality.
Below is my code for this - which doesn't work:
$('#form').submit( function() {
// Set the field array variables with data
$('button[name="action1"], [name="action2"]').each(function(index) {
alert('index : ' + index );
alert('value : ' + this.value);
});
$('button[name="action1"]').click(function(e) {
alert('ac1 clicked');
});
$('button[name="action2"]').click(function(e) {
alert('ac2 clicked');
});
my html buttons are:
<button id="submitButton" name="action1" value="action1" type="submit">action 1</button>
<button id="submitButton" name="action2" value="action2" type="submit">action 2</button>
Is there a way I can do this inside my form.submit, or a way to do the .click, which then submits the form. I am a little lost for a solution on this?
Please help :)
You can read the related target of the event object.
$('#form').on('submit', function(evt) {
if (evt.relatedTarget && $(relEl).is('input[type=submit]')) {
/* related element is a button - do something */
}
evt.preventDefault(); //cancel form submit, as required
});
In the button's click handler, set a hidden field before submitting the form. Then read the value of that hidden field in the request handler to find out which action was requested.
Bind a event handler to your buttons
$('button').on('click', function(e) {
var buttonId = $(this).attr('name');
if(buttonId = 'action1') {
// action1 was pressed
} else {
// action2 was pressed
}
$('#form').trigger('submit'); // trigger submit of form.
e.preventDefault();
});
First of, never include two dom elements with the same id on the same page. The class attribute is for such things. Change the id's of the buttons to submitButton1 and submitButton2 respectively and then this ought to work:
$('#submitButton1').closest('#form').submit(function() {
// first button action
});
$('#submitButton2').closest('#form').submit(function() {
// second button action
});
For standard HTML form submission :
HTML:
<form method="..." action="...">
...
<input type="hidden" name="action">
<input value="action1" type="submit" value="action 1" />
<input value="action2" type="submit" value="action 2" />
...
</form>
Javascript:
$('button[type="submit"]').on('click', function() {
$("#action").val(this.value);//where "#action" selects an input field (in the same form) of type="hidden"
});
For AJAX submission, do the same but read the action field's value back into javascript in the submit handler.

Getting How a Form Was Submitted on submit event

I have a form that has a couple of buttons on it. Two of the buttons use ajax to submit the form and clear it so that the user can add multiple records before moving on. The last button is for when the user is done with the page and wants to move onto the next page. Is it possible in jQuery's .submit() method to tell how the form was submitted (hitting enter, or get the object of the button clicked)?
Not sure if it is best practices, but I found that if I create a submit event handler and then after that create the handlers for the other buttons it seems to work okay, at least in Chrome.
Here's an example
$(function(){
$('form#frmField').submit(function(evt){
alert('Form Submitted');
return false;
});
$('input#btnReset').click(function(){
alert('Form Reset');
return false;
});
});
You can define onclick event handlers for your buttons which would save the state into some global-scope variable. Then you would check the state of the variable at onsubmit handler.
http://jsfiddle.net/archatas/6dsFc/
you can try this way:
HTML:
<form id="myform">
<input type="text" id="text1" name="text1" /><br />
<input type="button" class="button-submit" id="b1" name="b1" value="send 1" /><br />
<input type="button" class="button-submit" id="b2" name="b2" value="send 2" /><br />
<button class="button-submit" id="b3">send 3</button>
</form>
<br />
<div id="data"></div>
JS:
$('#myform').bind('submit', function(event, from) {
if(from)
$('#data').append("from :" + $(from).attr('id') + '<br />');
return false;
});
$('#myform').keypress(function(event) {
if (event.which == '13') {
event.preventDefault(); //preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that.
event.stopPropagation();
$(this).trigger('submit', [this]);
return false;
}
});
$('.button-submit').bind('click', function(event) {
event.stopPropagation();
$('#myform').trigger('submit', [this]);
return false;
});
example
event.preventDefault
jQuery events pass an event object through their calls. You can use this event object to determine how the event was called.
Specifically, if you pass it as a parameter e in the function, you can check e.type, which should be equal to click, or e.which, which if it was submitted with an enter, would be 13.
You can use target to find out which DOM element initiated the submission with e.target.
So,
jQuery('#foo').click(function(e){
var initiator = $(e.target); //jQuery object for the DOM element that initiated the submit
if(e.type==="click")
{
//is a click
}
else if(e.which==="13")
{
//is an 'enter' triggered submission
}
});
});

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources