How to execute code after html form reset with jquery? - javascript

After clicking an html reset button,
<input type="reset" />
I would like to execute some code. How can I do this and ensure that the form was reset prior to doing so?

I don't particularly like the idea of binding the reset event to the reset button instead of the form. A form can be reset by other means and in those cases your event will not trigger.
Instead, bind the function to the reset event but place it within an instantaneous setTimeout. It will ensure the form is actually reset prior to calling the function.
$('form').on('reset', function(e)
{
setTimeout(function() { /* ... */ });
});

Using a setTimeout as Ben does here is best: https://stackoverflow.com/a/21641295/144665
$("input[type='text']").val('Hello Everybody!');
$("input[type='reset']").closest('form').on('reset', function(event) {
// executes before the form has been reset
console.log('before reset: ' + $("input[type='text']").val());
setTimeout(function() {
// executes after the form has been reset
console.log('after reset: ' + $("input[type='text']").val());
}, 1);
});
You might want to narrow that form selector down to the specific form involved, maybe with an id.
Fiddle Proof: http://jsfiddle.net/iambriansreed/Zh5cd/

Update: use preventDefault instead of return false.
$('input[type="reset"]').click(function(evt) {
// Prevent the reset button from firing the form's reset event again
evt.preventDefault();
$(this).closest('form').get(0).reset();
// At this point your form's inputs should have their values reset
});
http://jsfiddle.net/EYqrX/1/

The suggestion is that instead of using <input type='Reset'> use <input type = "button"> in this way you do not have to stop the default behaviour of the reset button. You simply have to add the onclick attribute to the button and in the function you could call the form's reset method where ever you wish and control the behaviour as you wish. The following code illustrates that
HTML:
<input type="button" value="Limpiar" onclick="resetForm(this);"/>
JavaScript:
function resetForm(element) {
//Do what you need before reset the form
element.form.reset(); //Reset manually the form
//Do what you need after reset the form
}

try
$('your-form').bind('reset', function() {
alert('hi');
});

Here an example using the onreset event similar to how you normally use the onsubmit event of the form element to catch clicking on a submit button. The onsubmit example is added for clarification.
In your script:
function submitForm(form){
var xhr = new XMLHttpRequest(),
data = new FormData(form);
xhr.open("POST", url, true);
xhr.onload = function(event) {
switch (event.target.status){
case 200:
onSuccess(event);
break;
default:
onError(event);
}
};
xhr.send(data);
return false;
}
function resetForm(form){
var elements = form.elements;
// set some initial values to those form elements
return false;
}
In your html:
<form onsubmit="return submitForm(this);" onreset="return resetForm(this);">
<button type="submit">Save</button>
<button type="reset">Reset</button>
</form>

Reset the display contents when clicking the reset button.
$('.custom-file-input').on('change', function(){
const $label = $(this).next('.custom-file-label');
const fileName = $(this).val().split('\\').pop();
$label.data('default', $label.html());
$label.addClass('selected').html(fileName);
});
$('form').on('reset', function(){
$('.custom-file-input').each(function(){
const $label = $(this).next('.custom-file-label');
$label.html($label.data('default'));
});
});

I ended up using a promise to allow me to chain dom changes together. That way I can ensure the form is reset first, before resetting other dom stuff which needs to change based on input in the form, which includes resetting the form too. I don't necessarily expect the form reset to fail, so I don't use the reject function:
const form = document.getElementById("saveForm");
const resetBtn = form.querySelector("button[type=reset]");
resetBtn.addEventListener("click", function overrideReset(e) {
e.preventDefault();
return new Promise((resolve, reject) => resolve(form.reset())).then(() => {
//run code here.
});
});

would this help
$("input[type='reset']").on("click", function(){
alert("the form has been reset");
});
link to jsfiddle: http://jsfiddle.net/sdkTz/1/

Add a click event to the reset button, and have it look like this:
function(e) {
setTimeout(function() {
// your actual code here
},1);
}

Related

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

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

Inline onclick is overriding JQuery click()

A follow on from this question
Edit
JSFiddle code
As you can see if you run the code the button text does not change, the onclick is overriding the click function. If you remove the form id attribute from the function and the onclick attribute from the html tag the code works as expected (in a real scenario no onclick function implies a submit button rather than a button)
End Edit
I had thought that a typo was responsible for JQuery not firing the click() event when an inline event was specified, however I've run into the issue once more. Here's my code and the offending tag
<input id="submit1" type="button" onclick="this.disabled=true; doSubmit();" value="submit">
<script>myfunction('submit1', 'working', myformID)</script>
var myfunction = function(ID , text , formID) {
if(ID) {
var element = document.getElementById(ID);
if(formID) {
var form = document.getElementById(formID);
}
if (element) {
jQuery(element).click( function() {
if(jQuery(this).attr('disabled')) {
return false;
}
jQuery(this).attr('disabled' , 'disabled');
jQuery(this).attr('value' , processingText);
onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
if(form && !onclick) {
jQuery(form).submit();
}
jQuery(this).click();
});
}
}
};
I'm using javascript to create a function which will disable submit buttons while keeping any onclick attribute working in case of a doSubmit, like in this case. In other cases where the form id is set and there isn't an existing onclick I submit the form. Therefore if there is an issue with the html tag I need a general way to fix it with JS.
Many thanks in advance
Your inline handler disables the button: this.disabled=true;
Then jQuery handler checks if it is disabled and returns if so:
if(jQuery(this).attr('disabled')) {
return false;
}
There is, unfortunately, no way to predict the order of event handlers execution for the same event on the same element.
As a quick fix, I can suggest this:
Demo
jQuery(element).click( function() {
if(jQuery(this).attr('disabled-by-jquery')) {
return false;
}
jQuery(this).attr('disabled' , 'disabled');
jQuery(this).attr('disabled-by-jquery' , 'disabled');
jQuery(this).attr('value' , text);
onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
if(form && !onclick) {
jQuery(form).submit();
}
jQuery(this).click();
});

Is there a way to check if a postback is in progress?

In the case that a button is clicked multiple times on a page - Is there a way to figure out using javascript/jquery that a postback is already in progress and cancels the new attempt to submit the page?
Thanks
You can avoid users from double clicking by disabling whatever form elements can cause a form submit.
Checkout http://greatwebguy.com/programming/dom/prevent-double-submit-with-jquery/ for an example.
You can disable the button on first click, so that you could not click it when the post is in progress, and re enable it when the post-back has finished.
<script type="text/javascript" language="JavaScript">
var submitted = false;
function SubmitTheForm() {
if(submitted == true) { return; }
document.myform.submit();
document.myform.mybutton.value = 'Thank You!';
document.myform.mybutton.disabled = true;
submitted = true;
}
</script>
<form method="post" action="#">
<input type="submit" onclick=return SubmitTheForm()>
</form>
you could always just disable the button in the onclick handler.
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var self = this;
$(self).attr('disabled', 'disabled');
$.post('url',$(self).closest('form').serialize(), function() {
$(self).removeAttr('disabled'); // re-enable after request complete.
});
});
You could have your click event set a variable in your click handler to true and only allow the handler to proceed when the value is false. Of course you will have to set it to false again when your callback finishes.
if (!processInProgress) {
processInProgress = 1
// start the process
}

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