Question: How to handle consecutive button clicks in jQuery. For example I am submitting the form to server but in the meantime user clicks button again then duplicate request has been generated for the same. How to handle this efficiently in jQuery.
HTML Code:
<a id="submitBtn" href="javascript:void(0);"
onclick="login.validateLogin();"
class="btn btn-lg btn-success btn-block">Login</a>
jQuery code:
var login = {
validateLogin:function(){
$("#errormsg").hide();
login.validate();
if($('#loginForm').valid() === false){
return;
}
$("#submitBtn").prop('onclick',null);
/* Server request */
},
validate:function(){
$("#loginForm").validate({
ignore:"",
submitHandler: function(form) { return false; }
});
},
}
Disable the <submit> button or any other button which on clicked, submits the form, so only first click gets counted and the end user is prevented from clicking it. It is also semantic way of doing as just unbinding any event associated with the button while still allowing to click, will in some way confuse the users.
$("#loginForm").validate({
ignore: "",
submitHandler: function(form) {
$('#submitBtn').prop('disabled', true); // disable so it won't be clicked
return false;
}
});
Not sure why you have the .validate() method inside a function like that. The .validate() method is supposed to be called once and only used for initializing the plugin.
You should use a type="submit" button so that you can properly integrate with the plugin and enable/disable it much easier than trying to manually capture/deactivate/activate an anchor element. (Use CSS on the button element to make it look exactly like your anchor element.)
Then use .prop('disabled', 'disabled') within the submitHandler to disable the button as soon as the properly validated form is submitted.
As you can see by the demo, most of your code was not needed as the plugin takes care of nearly everything automatically.
$(document).ready(function() {
$("#loginForm").validate({ // <- initialize plugin on form
ignore: [], // <- proper way to set ignore to nothing
submitHandler: function(form) {
$('#submitBtn').prop('disabled', 'disabled');
alert('submitted'); // <- for demo
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<form id="loginForm">
<button id="submitBtn" class="btn btn-lg btn-success btn-block">Login</button>
</form>
Related
I have a form which is validated using the jQuery validation plugin. I added the bootstrap confirmation on the submit button. Everything is working fine, except that I want the bootstrap confirmation to appear on the submit button when the form no longer has any errors.
I've tried doing this:
HTML code:
<button type="submit" class="btn" id="submit_button" data-toggle="confirmation"data-popout="true">Submit</button>
jQuery code:
$("#submit_button").on('click', function(){
if($('#form').valid()) {
$(this).trigger("confirmation");
}
});
But it didn't do anything. Should I use the submitHandler in jQuery validation? Or is this not just possible?
Should I use the submitHandler in jQuery validation?
YES, of course.
Use the submitHandler for this. As per documentation, it fires only when the form is valid, so there's no need to test the form's validity or use another click handler.
$('#form').validate({
// options, etc.
submitHandler: function(form) { // fires when valid (and on button click)
$("#selector").trigger("confirmation");
}
});
I have the following jsp:
...
<script type="text/javascript">
$(function() {
// prevent multiple submissions
$('#saveCallListBtn').one("click", function() {
$('#callListForm').submit();
});
});
...
</script>
...
<form:form id="callListForm" commandName="callList" action="${contextPath}/calllist/save" method="POST" htmlEscape="true">
...
<td colspan="2" style="text-align: center">
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
</td>
...
</form:form>
The behavior I am looking for is to only all the form to be submitted once no matter how many times the save button is clicked. Using the jQuery .one function, I can get the above code to correctly work. As the form will submit multiple times if I click more than once.
The following code will work fine:
$('#saveCallListBtn').on("click", function() {
$(this).prop("disabled", true);
$('#callListForm').submit();
});
But I am interested to know what I am doing wrong with the .one function.
Note the type here:
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
A submit button in a form will submit the form, no JavaScript required. So when your handler is automatically removed, on the next click the default handling (submitting the form) occurs, courtesy of the browser.
The only reason you're not seeing the form submitted twice on first click, I suspect, is that the act of submitting the form begins the process of tearing down the page to make room for the result of the submission.
FWIW, I would suggest that you not have a click handler on the button, but rather a submit handler on the form that, if all is well and it's going to allow submission to occur, disables the button and sets a flag to prevent future form submission, since forms can be submitted in multiple ways. (On some forms, pressing Enter in a text field will do it, for instance.)
E.g.:
$("#callListForm").on("submit", function(e) {
var $btn = $("#saveCallListBtn");
var valid = !$btn.prop("disabled");
if (valid) {
// ...do any other validity checks you may want, set `valid` to false
// if problems encountered...
}
if (valid) {
$btn.prop("disabled", true);
} else {
e.preventDefault();
}
});
The jQuery one function will execute the event handler only once. However, the default behaviour of the element clicked will execute indefinitely.
Change the type of the button to button, such that it has no default behaviour:
<input id="saveCallListBtn" type="button" value="Save" class="button-med"/>
I'm still a newb when it comes to MVC, Ajax and JavaScript. I have an application where I have to make a change. Right now, when a change is made and the Save, the spinner displays as the info saves and the page loads. The code for the Save looks like this:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
});
HTML looks like this:
<input type="submit" value="Save" class="btn btn-block btn-primary user-action" name="action:Save" id="SaveButton" />
Just a note there multiple buttons on the screen so it is using the "Multiple Button" solution from How do you handle multiple submit buttons in ASP.NET MVC Framework?
The following code was added:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
displaySavePromptMessage();
});
function displaySavePromptMessage() {
if (isModalOpen == false) {
bootbox.dialog({
closeButton: false,
title: "",
message: "<strong>Warning: </strong>Changes have been made, ensure corresponding dates have been updated on the screen",
buttons: {
success: {
label: "Ok",
callback: function () {
navParams.userAction = false;
}
}
}
});
}
}
Now what's happening is the save button is clicked, the spinner starts running, the dialog box loads, but before the OK button is clicked the dialog button closes and the spinner stops. The changes are saved.
What needs to happen is the spinner starts, the dialog box loads and everything stays as is until the user clicks OK. Then the processing continues. I'm not sure how to make this happen. Any thoughts?
Basic concept. You need to listen to submit event and prevent it:
$('.some-form').on('submit', function(submitEvent) {
submitEvent.preventDefault();
});
Then in your handler, you need to submit your form on success:
// Inside your success handler
$('.some-form').get(0).submit();
You have input type="submit" which will submit the form when this button is clicked. Either change this to type="button" or as #Lesha Ogonkov said
$('#yourFormID').on('submit', function (e) {
e.preventDefault();//it will stop loading page on form submission
});
in ajax inside you success handler function
$('.myFromID').get(0).submit();
I am trying to post a form using ajax after a form has been validated. However the .valid seems to be wrong.
Multiple action type is desired based on button.
This example is also not showing the errors messages correctly upon submit
$('#submit').click( function(){
alert(validator.valid());
});
$('#submit2').click( function(){
alert(validator.valid());
//do something else
});
status become true if i enter a required field (e.g name)
this is the fiddle
try this fiddle
http://jsfiddle.net/r2HUu/4/
It's working. I just checked form' validation by $("#myForm").valid()
Quote OP:
"I am trying to post a form using ajax after a form has been validated"
As per documentation, your ajax goes inside the submitHandler callback function.
submitHandler (default: native form submit) Type: Function()Callback
for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it validated.
Using this callback, the click is captured automatically and the function is only fired on a valid form.
$(function () {
var validator = $("#myForm").validate({
// rules and options,
submitHandler: function(form) {
// your ajax goes here
alert("valid form");
return false;
}
});
});
DEMO: http://jsfiddle.net/fXDwd/
Quote OP:
"However the .valid seems to be wrong."
EDIT
As per OP's comments and updated jsFiddle:
If you want to have multiple submit buttons do different things on one form, construct click handlers for each button which you've already done. Now you must move those buttons to outside of the <form></form> container. Otherwise, the plugin will treat them both as normal submit buttons and interfere with your click handlers.
The other problem is your implementation of .valid(). Attach it to the form element, $("#myForm"), not the validator initialization object.
HTML:
<form id="myForm" action="">
...
</form>
<input type="button" id="submit" value="Submit form" />
<input type="button" id="submit2" value="Submit form2" />
jQuery:
$(function () {
var validator = $("#myForm").validate({
// rules and options
});
$('#submit').click(function () {
alert($("#myForm").valid());
//do something
});
$('#submit2').click(function () {
alert($("#myForm").valid());
//do something else
});
});
DEMO: http://jsfiddle.net/vfrGU/
I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.
It's quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?
Buttons like <button>Click to do something</button> are submit buttons.
Set type="button" to change that. type="submit" is the default (as specified by the HTML spec):
The missing value default and invalid value default are the Submit Button state.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button" your form will not be submitted.
<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.
function forms_ini(){
for(var form of document.getElementsByTagName('form')){
form.addEventListener('submit', function(ev){
ev.preventDefault()
})
}
}
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}