I am using following form and submit button in my dynamic html page.
<form method=\"post\" class=\"my-form\" >
and
<input type=\"submit\" name=\"submitButton\" value=\"Submit\" id=\"button1\" />
What I am trying to do is when a particular input is provided by user, then display an alert box asking if user wants to submit the change or just stay on the same page without submitting the change.
I can display the alert box (with help from stackoverflow members) but along with window.alert what I should add to JavaScript so the form is not submitted if user clicks "cancel" on window.confirm and the form is submitted if user clicks "ok" on window.confirm?
JavaScript example is at fiddle
$(document).on('input', '.my-input', function(){
$(this).closest('form').addClass('changed');
});
$(document).on('submit', '.my-form', function(e){
if($(this).hasClass('changed')){
var x=window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
if (x)
window.alert("Thresholds changed!")
else
window.alert("Thresholds not changed!")
}
$(this).removeClass('changed');
e.preventDefault();
});
You just need to change your logic so that preventDefault() is only called when the user declines the confirm box. Try this:
$(document).on('submit', '.my-form', function (e) {
if ($(this).hasClass('changed')) {
var allowSubmit = window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
if (!allowSubmit)
e.preventDefault()
}
});
Example fiddle
If you click 'OK' you'll see that the form is submit (and a warning from jsFiddle to use a POST request - but that's normal), whereas clicking 'Cancel' does nothing.
You can also return false in your submit function handler, it should work. Check this question for an example.
I want to prevent multiple form submissions, but I need to have the value of the submit element posted back to the server (so that I know which button the user clicked on).
Most of the Internet Wisdom concerning suppression of multiple form submissions seems to involve disabling the submit button during form submission. This prevents the button from being clicked a second time, but also prevents its value from being posted.
I've found a few examples of JS code that hides the submit button(s), which allows their values to be posted. But those examples all replace the (now hidden) button with some sort of "processing..." message. I really want a solution that presents the user with a disabled button but still posts the button value.
I should add that I'd prefer a solution that works with standard HTML one would find in most forms. No magic IFrames, hidden fields, id or class names, etc. I want a JS function I can stash away in a library and reference from all of my existing forms to enable this new behavior.
(I have a solution, which I will post as an answer. But I had to ask the question to comply with the Zen of SO.)
Here is (yet another) answer to the question of how to deal with preventing the user from clicking on the form submission button more than once. This solution makes it appear that the button has been disabled.
Under the covers, it creates a disabled button to display to the user, and hides the actual button so that its value is posted. I also move the hidden button so that the extra element doesn't mess up CSS selectors.
Also note the check for invalid form fields. If you omit this check, and form validation fails, then the user winds up with a form that wasn't posted (because client-side validation failed) but the buttons are disabled.
// Disables buttons when form is submitted
$('form').submit(function () {
// Bail out if the form contains validation errors
if ($.validator && !$(this).valid()) return;
var form = $(this);
$(this).find('input[type="submit"], button[type="submit"]').each(function (index) {
// Create a disabled clone of the submit button
$(this).clone(false).removeAttr('id').prop('disabled', true).insertBefore($(this));
// Hide the actual submit button and move it to the beginning of the form
$(this).hide();
form.prepend($(this));
});
});
Because you can submit a form other ways than simply clicking the submit button it's better to add a listener to the form's submit event rather than the click event on the submit button. This jQuery event listener should work on any form and prevent it from being submitted more than once.
$('form').on('submit', function(e) {
if (!$(this).data('submitted')) {
$(this).data('submitted', true);
}
else {
e.preventDefault();
}
});
To make the form look disabled you could add some css that makes the form look disabled and then add the classname on form submission.
$('form').on('submit', function(e) {
if (!$(this).data('submitted')) {
$(this).data('submitted', true).addClass('disabled');
}
else {
e.preventDefault();
}
});
I wanted to stop the user from causing multiple form submissions by double clicking the submit button or hitting the enter key twice. I like this solution, because it doesn't require a hidden form field or hiding the submit button.
The two key points are:
Return true/false instead of using e.preventDefault() and form.submit(), because form.submit() doesn't know which button was clicked and therefore, can't pass the button name/value.
Disable the button with pointer-events: none; instead of disabled="disabled", because the disabled attribute won't send the button name/value. I believe pointer-events: none; is not supported by Internet Explorer 10 or below.
javascript/jquery code:
var form_selector = 'form',
button_selector = 'button, input[type=submit], input[type=button], input[type=reset]',
deactivated_classname = 'state-submitting',
deactivated_class = '.'+'state-submitting';
// Capture the submit event so it will handle both the
// enter key and clicking the submit button.
$(document).on('submit', form_selector, function(e) {
var form = e.target,
buttons = $( form ).find( button_selector );
// Returns, because the form is already being submitted by a previous attempt.
if( $( form ).find( deactivated_class ).length > 0 ) return false;
disableButtons( buttons );
// Safari (version 11) bugfix: Safari needs a timeout or it won't
// show the deactivated styles.
setTimeout(function() {
// Must use return true, because using form.submit(), won't pass the button value.
return true;
}, 50 );
});
function disableButtons( buttons ) {
// Disables all buttons in the form.
$( buttons ).each(function( index, elem ) {
$( elem ).addClass( deactivated_classname );
});
}
For AJAX forms, you will want to re-enable the buttons after the response is returned.
$( document ).on( 'ajax:complete', form_selector, function(e) {
var form = e.target,
buttons = $( form ).find( button_selector );
enableButtons( buttons );
});
function enableButtons( buttons ) {
$( buttons ).each(function( index, elem ) {
$( elem ).removeClass( deactivated_classname );
});
}
CSS:
// The button is disabled while it is submitting.
.state-submitting {
// Turns off hover and click events. Not supported in IE 10 and below.
pointer-events: none;
opacity: 0.5;
}
You can simulate disabled look behavior. E.g. if you have a button like this:
<input id="btn" type="button" onclick="disableMe(this)" value="Submit" />
You can define CSS like this
.disabled {
backround-color:grey;
color:darkgrey;
}
And JS like this
function disableMe(btn) {
btn.className = "disabled";
btn.onclick = function(){return false}
}
What will happen - on first click button will become grey (via applied CSS) and onclick event will change to "return false" for all the consecutive calls preventing future click actions. The button will appear and act as disabled, but will not be, so it will not prevent button submission.
Here's a couple options:
1. You could create hidden inputs and dynamically change the value of it before the form is submitted either onClick or onHover of the said button:
2. You could create an hidden iframe which is the target of the said form. Once the submit button is click, you could cancel the submit event, grab all of the data and send it programatically through the iframe instead.
I was having the same issue as OP, and I found that disabling the submit button(s) after a short (maybe 0 seconds) timeout via setTimeout does the trick. The submit button's name value is still posted with the rest of the form data as desired, but the button disables itself (almost) immediately, preventing further clicks.
The timeout is a bit ugly, but it seems preferable to more elaborate swapping/covering schemes.
This could be combined with also altering the form's onsubmit property for extra precaution, but I'm not doing that in the example below for clarity's sake. Either way, I like the appearance/behavior of a disabled button after the first submission click… the user experience seems better to me… it's more clear what's happening.
My form element's start tag:
<form onsubmit="return formSubmit(this);" method="post" action="">
In my JavaScript (sorry, I'm not up-to-date with the latest JS tech like jQuery, etc, so I'm posting this in old-fashioned-native-JavaScript-5-with-no-dependencies-compatible code):
function formSubmit(form) {
// MUST DELAY so as not to break input/button[type=submit] name submission
setTimeout(function () {
var els = form.elements;
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.getAttribute('type') == 'submit') {
el.setAttribute('disabled', 'disabled');
}
}
}, 0);
return true;
}
I think better solution would be to use JQuery :
<form onsubmit="$('#submit').hide();" method="post" action="">
No chance of double clicking.
Sometimes we use name field in submit button for validation so if this is disabled then that could failed.
Using .hide() the button will be hidden.
so no chance of double clicking it.
Be honest with you I was not able to understand fully most of the posts on this page, but I think I have faced this problem before, and solved it by allowing the page to post the first time the button is clicked, so when the page comes back from server it has the new value assigned to it, and it looks clickable, and enabled. But if a 2nd attempt is made to press it, then it becomes disabled, and page will not post, and send to the server again by clicking this button. I hope this helps:
#section scripts
{
<script type="text/javascript">
$('#edit').click(function () {
if (document.getElementById("edit").value == '') {
// This portion should execute onlythe
// first time button is clicked, and it
// will assign a new value to the button,
//and posts the value
//to the server
}
else {
edit.disabled = true;
}
});
</script>
}
A much much much simpler way is to enclose whatever code you use to disable the button in a setTimeout() with 0 delay. That way the button is still enabled in the thread that handles the form submission while another parallel thread is spawned to do the disabling.
Example (using jQuery):
<form method="POST" onsubmit="javascript:setTimeout(() => $('*[type=submit]', this).attr('disabled', 'disabled'), 0)">
I have a long form that I am validating with the jQuery validate plugin. After the form validates, I want the submit button to change into a confirm button with an appropriate message above about checking the form for errors. This button, when clicked again, should submit the form for real this time as long as all the required fields are still filled in.
I have the following:
var confirmed = function(){
alert($("#someForm").attr("name")); //just to see the function fire...
$("#someForm").submit();
return true;
}
$(document).ready(function(){
$("#someForm").validate({
submitHandler: function(form){
var oldBtn = $("#submit");
var newBtn = oldBtn.clone();
newBtn.click(confirmed)
newBtn.text("Confirm");
newBtn.insertBefore(oldBtn);
oldBtn.remove();
newBtn.attr({"id": "submit"});
}
});
});
...
<button type="submit" id="submit">Submit</button>
It works to validate the form, then the button changes text, the the function fires (the alert has the name of the form in it) when clicked, but the form never submits for real.
Any help or ideas would be greatly appreciated.
Thanks
EDIT:
Ok, I think I have figured it out. I have the submit button hidden and a button called Validate that just checks if the form is validated without submitting using $("#someForm").valid(); If it checks out, I hide the "Submit" button and show the "Confirm" button along with a little message about checking your submission, etc. See below:
$(document).ready(function(){
$("#submitBtn").hide();
$("#confMessage").hide();
$("#someForm").validate();
});
var checkValid = function(){
var isValid = $("#volunteer").valid();
if(isValid){
$("#validBtn").remove();
$("#submitBtn").show();
$("#confMessage").show();
}
}
...
<p id="confMessage">Please review your submission.</p>
<p><button id="validBtn" onclick="checkValid()">Validate</button>
<button type="submit" id="submitBtn">Submit</button></p>
Works perfectly, and is a heck of a lot cleaner than my original code!
remove oldBtn.remove(); then it will work.
You have
var oldBtn = $("#submit");
var newBtn = oldBtn.clone();
What above line doing is adding same DOM in html so that mean ID will be copied too.
And ID must be unique for each DOM.
Try to rewrite ID for cloned DOM and try.
AND
newBtn.click(confirmed)
This code means you are assigning event to newBtn not calling click event.
For call a click event use .trigger()
I am using ajax using jquery, I am deleting a row using the following code snippet:
$('#example a.delete'). live('click', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete this row?"))
{
alert("Hello World!")
}
});
When I click grid view show button, grid view appears without page refreshing due to ajax. If I click grid view show button more than one time, it refresh again grid view area, accordingly. But confirm box show more than one time,which is equal to my no. of clicks on grid-view show button, when I click on a single row delete button.
How can avoid this !
Edited
HTML CODE:
<td><a class="delete" href="#" style="margin-left: 10px"><img src="images/delete-icon.png" width="16px" height="16px" /></a></td>
Edited
Complete Code Snippet:
$('#example a.delete'). live('click', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete this row?"))
{
$getCode = $(this).parent().parent().attr('id');
var oTable = $('#example').dataTable();
var index =oTable.fnGetPosition( document.getElementById($getCode) );
$.post("DeleteDepartment", {
depID:$getCode
}, function(data) {
if(data.result >0){
var oTable = $('#example').dataTable();
oTable.fnDeleteRow( index );
}else{
alert("Operation Fail");
}
});
}
});
$('#example a.delete').unbind('click').bind('click', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete this row?"))
{
alert("Hello World!")
}
});
You appear to be attaching multiple events to the button. Are you sure you're only calling live() ONCE, and once only? If you call it multiple times, you get multiple handlers.
(Of course, this is why I prefer to just use .onclick = function() {...} personally)
It looks like the code is written to do the confirm once for each click.
If you want it to confirm only once you have to make the code remember that you already confirmed.
The row is not deleted until the server calls your success callback function. During that time you can keep clicking on the row and firing the click event.
You could set a variable or a property on the row when the user confirms and then check this variable each time they click. Only show the confirm message if the variable is not set.
Or you could change the state of the element you click, change its image, change style, set an attribute. You could both inform your code that it has been clicked and indicate to the user that the row is already marked for deletion.
Or you could try jquery's .one() method to attach the event.
For some weird reason i'm getting my confirm box coming up twice. here is my code:
$(".DeleteComment").live("click", function(){
var CommentID = $(this).attr("rel");
var confirm
if (!confirm('Are you sure you want to permanently delete this comment?')){
return false;
}else{
$(this).html("loading").css("color", "#999");
//AJAX HERE
return false;
}
});
Do you load any content dynamically (via ajax)? It could be the case that the click event is bound to the same element twice resulting in the double confirmation.
It happens when we bind event on the elements which are loaded dynamically via AJAX
So for example we are loading some dynamic html content (e.g. dynamic content in modal) on click of the edit form button,
And in that content if we have binded click event on some button e.g. delete button, then every time we click on edit form button, it binds the click event to delete button every time,
And if you have set confirm box on click event of delete button then, it will ask you as many time as it was binded for that click event means here if we have clicked edit form button 5 times then it will asks for your confirmation 5 times.
So for solving that issue you can unbind the event every time before binding event to dynamically loaded element as following :
$(document).off('click', '.DeleteComment').on('click', '.DeleteComment', function () {
if (confirm('Are you sure you want to permanently delete this comment?')){
//Delete process
return true;
}
return false;
}
Or Another way to solve this problem is to add your script in main page, means static page not in dynamically loaded one.
try this:
$_blockDelete = false;
$(".DeleteComment").live("click", function(event){
event.preventDefault();
//event.stopPropagation(); // it is not necessary
if (!$_blockDelete)
{
$_blockDelete =true;
var rconfirm = confirm('Are you sure you want to permanently delete this comment?');
if (rconfirm)
{
$(this).html("loading").css("color", "#999");
var CommentID = $(this).attr("rel");
//AJAX HERE
//return the value "false" the variable "$_blockDelete" once again ajax response
}
}
});
Did you try removing that not-used var confirm?