So by default Semantic-ui doesn't have any way to prevent clicks which trigger the validation, once the form has been setup, as the validation is handled onsubmit directly. This is important if you have multiple buttons on the page and only want some to trigger the validation and the rest perhaps to be able to postback, or do other things minus triggering the form validation.
I checked some answers that talk about changing the input from a type=submit to a type=button, but you lose the design ability especially the ability to add an icon and is not the ideal solution.
Am posting this question, since my answer to this question, got deleted by the moderator, even though I have a working fiddle and a detailed answer on how to achieve this.
Reposting the entire answer here, incase anyone needs help on this.
I was able to implement this in a different way, as the button type=button control while ignoring the validations, did not submit, and if I did submit manually the default event handler of semanticui would intervene and show the validation errors.
My use case two buttons, one a save draft and the other a finalize (final save). The first one had to save the data as is, without triggering the validations, while the other would trigger validations and then save.
I am also implementing all the validators using data attributes that I custom implemented for this project, hence the form validator is inside a JS file.
In my form validation's failure method, I included a delegate function which I could set on my page and depending on which button clicked it, then be able to return true or false.
My form validator inside a JS file
$('.ui.form').form({
inline: true,
on: 'submit',
fields: formFields,
transition: 'fade',
keyboardShortcuts: false,
onFailure: function () {
var returnValue = false; //Default to false, since validations failed
//If the delegate is present, fire it to evaluate
if (typeof window.delegValidate == 'function') {
returnValue = window.delegValidate();
}
//Ignore the toast if the delegate evaluated to TRUE
if (!returnValue) {
$('body')
.toast({
title: 'Unable to save',
message: 'Please enter all required field data before saving.',
classProgress: 'red',
showProgress: 'top',
progressUp: true,
position: 'bottom right',
showIcon: 'red exclamation triangle'
});
}
return returnValue; // false is required if you don't want to let it submit
}
});
and on my page I attached a function to the window, since my form validation is inside a JS file.
Page function
//For all postback buttons, save the id value in a hidden field for use in the delegate
$('.postbackButton').bind('click', function (e) {
$('#ButtonClicked').val(this.id); // a hidden field on the page
});
//setting the delegate for use in the form validations
window.delegValidate = function () {
//For the save button, just ignore the validations and return true
//This in turn is invoked by the failure method of the form validation that is
//dynamically attached to the page, and hence this return value is respected
//over the false that is otherwise sent back for when we want to interrupt the page
//since there are errors normally.
if ($('#ButtonClicked').val() == 'Save')
return true;
else // if value is finalize, let it return false
return false;
}
For other pages where I don't want this functionality, I can simply not write the delegate method and the default validation fires as expected on the submit button.
Also posted here Ignore SemanticUI validation on some buttons
Hope this helps anyone looking for a better way of handling this scenario.
I am using jQuery Validator to validate a form and I wanted to disable the fields that were blank when the user clicks submit so that the server does not receive any data from the inputs that were left blank. To disable them, I used the following Javascript:
$(function() {
$("#form1").submit(function() {
$(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
return true; // ensure form still submits
});
});
Here is my problem: This code works great assuming the form was validated on the first submission. However, if the user hits submit but it was not validated, all of the alerts for various required fields and such pop-up, but all of the inputs are disabled. How can I fix this? I need to know how to re-enable them if the form is not validated and properly submitted.
It doesn't make sense to disable the field to submit. Rather—you should first do a front-end only validation that prevents submitting if there are empty fields (and those fields are required to not be empty).
You can set up a variable (or a function) to run through your validation and only submit if it returns true. This is a condensed example of just one input.
var validate = ($('input').val() == '') ? false : true;
if(validate){
// submit your form
} else {
// throw your errors
}
Then it would be good to clear your errors at the beginning of your validation.
I'm using
$('#myform')[0].reset();
to clear HTML form fields when a clear button is clicked. I'm also using jquery.validate.js. So when the above runs, it triggers form validation. All form fields with any validation then display their error messages. How do I prevent this?
I have tried this but it didn't do anything:
$('#myform').removeAttr("nonvalidate");
From the question you linked, the answer is what you want... All you have to do is capture the reset event and call v.resetForm().
var v = $('form').validate(); //etc etc whatever you have here, the important part is saving "v"
$('form').on('reset',function () {
v.resetForm();
});
See it working here: http://jsfiddle.net/uuu8jerr/
I have lots of different forms on my website. I want to use Jquery to:
Display an error message if any of the text fields are blank
Highlight the blank fields with CSS
Prevent submission of the form until the user fills them in.
All the different forms link to the same Jquery script, so I have to make sure that my jquery doesn't make any references to a specific form (otherwise, I will have to write a different script for each form).
I thought the best way to do this would be to an each function to loop through the input fields to check if they are blank and then use event.preventDefault(); to stop the form from submitting and addClass to highlight the fields.
The each function works but the preventdefault/addclass don't seem to work. I'm not sure what I am doing wrong. Here is my code: (JSFiddle version)
$(document).ready(function () {
$('.names').submit(function(){
$('.names input[type=text]').each(function(n,element){
if ($(element).val()=='') {
event.preventDefault();
alert('Some fields are blank (highlighted in red). Please fill them in');
($element).addClass("error");
return false;
}
});
return true;
});
});
How can I get it to work? Also would it be possible to apply the error class to the parent <p> tag of the input field rather than the field itself?
event is undefined. Catch the parameter in your submit-callback and invoke preventDefault on that:
$(document).ready(function () {
$('.names').submit(function (e) {
$(this).find('input[type=text]').each(function (n, element) {
if ($(element).val() == '') {
e.preventDefault();
alert('Some fields are blank (highlighted in red). Please fill them in');
$(element).parent().addClass("error");
return false;
}
});
return true;
});
});
Note that:
($element) is also undefined, you meant $(element).
To add the error class to the parent, use $(element).parent().
This wont work if you have multiple forms. Use $(this).find('input[...]') instead of $('.names input[...]'). This way, you only validate the form that you are submitting.
Here is a working fiddle.
I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.
I googled and googled and found a few scripts, but none of them seem to be sufficient.
How can I prevent these duplicate entries from occurring using javascript or preferably jQuery?
Thanx in advance!
How about disabling the button on submit? That's what I do. It works fine.
$('form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Disclaimer:
This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.
I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.
This should do the trick:
$("form").submit(function() {
$(":submit", this).attr("disabled", "disabled");
});
No JQuery?
Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.
One technique I've seen used is to assign a unique ID to every form that's opened, and only accept one submission per form based on the ID.
It also means you can check how many times people aren't bothering to submit at all, and you can check if the submission genuinely came from your form by checking if it's got an ID that your server created.
I know you asked for a javascript solution, but personally I'd do both if I needed the robustness.
Preventing the double posting is not so simple as disabling the submit button. There are other elements that may submit it:
button elements
img elements
javascripts
pressing 'enter' while on some text field
Using jQuery data container would be my choice. Here's an example:
$('#someForm').submit(function(){
$this = $(this);
/** prevent double posting */
if ($this.data().isSubmitted) {
return false;
}
/** do some processing */
/** mark the form as processed, so we will not process it again */
$this.data().isSubmitted = true;
return true;
});
Here is bit of jQuery that I use to avoid the double click problem. It will only allow one click of the submit button.
$(document).ready(function() {
$("#submit").on('click', function() {
});
});
I'm not sure what language/framework you're working with or if it's just straight HTML. But in a Rails app I wrote I pass a data attribute on the form button disable_with which keeps the button from being clickable more than once while the transaction is in process.
Here's what the ERB looks like.
<%= f.button "Log In", class: 'btn btn-large btn-block btn-primary', data: {disable_with: "<i class='icon-spinner'></i>Logging In..."} %>
This is what I came up with in https://github.com/liberapay/liberapay.com/pull/875:
$('form').on('submit', function (e) {
var $form = $(this);
// Check that the form hasn't already been submitted
if ($form.data('js-submit-disable')) {
e.preventDefault();
return false;
}
// Prevent submitting again
$form.data('js-submit-disable', true);
// Set a timer to disable inputs for visual feedback
var $inputs = $form.find(':not(:disabled)');
setTimeout(function () { $inputs.prop('disabled', true); }, 100);
// Unlock if the user comes back to the page
$(window).on('focus pageshow', function () {
$form.data('js-submit-disable', false);
$inputs.prop('disabled', false);
});
});
The problem with the method described here is that if you're using a javascript validation framework and the validation fails, you won't be able to correct and re-submit the form without refreshing the page.
To solve this, you need to plug into the success event of your validation framework and only then, set the submit control to disabled. With Parsley, you can plug into the form validated event with the following code:
$.listen('parsley:form:validated', function(e){
if (e.validationResult) {
/* Validation has passed, prevent double form submissions */
$('button[type=submit]').attr('disabled', 'disabled');
}
});
If you are using client-side validation and want to allow additional submit attempts if the data is invalid, you can disallow submits only when the form content is unchanged:
var submittedFormContent = null;
$('#myForm').submit(function (e) {
var newFormContent = $(this).serialize();
if (submittedFormContent === newFormContent)
e.preventDefault(true);
else
submittedFormContent = newFormContent;
});
Found at How to prevent form resubmission when page is refreshed (F5 / CTRL+R) and solves the problem:
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
That is what I did to solve the problem.
I disabled the button for a second with adding setTimeout twice:
- the 1st time is to let the JS form fields verification work;
- the 2nd time is to enable the button in case if you have any verification on your back end, that may return an error, and hence the user will want to try to submit the form again after editing his data.
$(document).ready(function(){
$('button[type=submit]').on("click", function(){
setTimeout(function () {
$('button[type=submit]').prop('disabled', true);
}, 0);
setTimeout(function () {
$('button[type=submit]').prop('disabled', false);
}, 1000);
});
});