I have a function to test and make sure at least one form field is filled out:
function checkFields(form) {
var checks_radios = form.find(':checkbox, :radio'),
inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]');
var checked = checks_radios.filter(':checked');
var filled = inputs.filter(function(){
return $.trim($(this).val()).length > 0;
});
if(checked.length + filled.length === 0) {
return false;
}
return true;
}
And that is called when the form is submitted:
$(function(){
$('.checkThisForm').on('submit',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
/* ??? */
}
});
});
What goes in my else { } to allow the form to submit if the user has supplied at least one element to search for in the form?
return for form action will indicate to proceed or stop the submission
$('.checkThisForm').on('submit',function(e){
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
return false;
}
return true;
});
you are required to follow below info. First you need to triger click event and submit
$(function(){
$('.checkThisForm').on('click',function(e){
e.preventDefault();
var oneFilled = checkFields($(this));
if (!(oneFilled)) {
alert('You must fill in at least one field');
} else {
this.submit();
}
});
Related
I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});
I have a code that execute the submit event from the form and I want the modal stay open if the validation is false, but it doesn't work.
var myForm = document.updteform;
var condition = true;
if(myForm.pass1.value !== myForm.pass.value){
alert("Password Doesn't Match, Please try again.");
myForm.pass1.focus();
condition = false; //it will return the value
}
After that... this code below will execute.
if(!condition) {
if(evt.preventDefault) { event.preventDefault(); }
else if(evt.returnValue) { evt.returnValue = false; }
else { return false; }
}
}
This one works...
Step 1: create an onlick that calls the function to your JavaScript
Step 2: create a function:
function changePass(){
var oldpass = document.getElementById("password1").value;
var newpass = document.getElementById("password2").value;
if (oldpass != newpass) {
alert("Password Doesn't Match Please try again.");
return false; //the modal will not close because it doesn't return a value.
} else {
document.getElementById("form_id").action = "<?= base_url('index.php/Employee/updateUser'); ?>"; // Setting form action to your Controller page.
document.getElementById("form_id").submit(); // Submitting form
}
}
That say so.. Hopefully it'll help :)
I have a form where I'm using twitter typehead & the problem is whenever twitter typehead loads it creates another input field that is blank ¬ shown to user
Now i have this function to validate all inputs
var fields = $('#second_step input[type=text]');
var error = 0;
if (!$("input[name='career']:checked").val()) {
alert('Please Select yes or no'); return false;
}
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')]) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if (!$('#reg').valid()) {
return false;
}
Now due to that typehead input whic has no name or id it just have a certain class tt-hint & this input is read only how can i just skip this input from my above validation?
You can use jQuery's NOT function.
var fields = $('#second_step input[type=text]').not('.tt-hint');
You can filter out the fields with:
var fields = $('#second_step input[type=text]:not(.tt-hint)');
Your input has typeahead applied by using a class selector .typeahead.
So in your case you could use the :not pseudo-class selector to filter them out:
var fields = $('#second_step input[type=text]:not(.typeahead)');
That way you skip the typeahead fields.
Personally I would ignore disabled fields, since the user cannot correct them if there is an error. You say the input is read only so that would seem to correlate.
$('#second_step input[type=text]').filter(function(){ return !this.disabled; })
Try this :
fields.each(function(){
var value = $(this).val();
if($(this).hasClass('tt-hint') {
$(this).addClass('valid');
} else {
if( value.length<1 || value==field_values[$(this).attr('id')]) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
}
});
if (!$('#reg').valid()) {
return false;
}
This is part of my jquery function that validades a form i have on my website:
/*
validates errors on all the fieldsets
records if the Form has errors in $('#formElem').data()
*/
function validateSteps(){
var FormErrors = false;
for(var i = 1; i < fieldsetCount; ++i){
var error = validateStep(i);
if(error == -1)
FormErrors = true;
}
$('#formElem').data('errors',FormErrors);
}
/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateStep(step){
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == ''){
hasError = true;
$this.css('background-color','#FFEDEF');
}
else
$this.css('background-color','#A8FC9C'); /* Campo preenchido */
});
var $link = $('#navigation_form li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError){
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
/*
if there are errors don't allow the user to submit
*/
$('#enviar_candidatura').bind('click',function(){
var preenchimentoForm=true;
if($('#formElem').data('errors')){
preenchimentoForm=false;
dadosFormularios(preenchimentoForm);
//return false;
}
else{
dadosFormularios(preenchimentoForm);
}
});
});
However, i'm using too LiveValidation (http://livevalidation.com/) to validade fields client-side. Obiously, if the part validated by jquery is Ok, doesn't matter if there's errors on the LiveValidation part because the form is submitted.
So, what i want is to add an if clause or something like that inside this jquery code to verify if there are LV_invalid_fields. If 'yes' then block form from submitting like it's done with the jquery validation part, but i don't know how to do it neither where is the right place in the code above to put this verification. I would appreciate some help. Thanks!
//... live validation codes here
$("#myform").submit( function (event) ) {
event.preventDefault();
if ($(".LV_invalid").length > 0) {
//do not submit
}
else {
//do form submission here
}
}
First, you have to change the binding on the click to a binding on the submit action on the form.
And your function must return false on the submit action to stop the submitting action.
So, change your code like this :
$('#formElem').submit( function (event) ) {
var preenchimentoForm = true;
if ($('#formElem').data('errors')){
preenchimentoForm = false;
}
return preenchimentoForm;
}
You can read some explications about unobtrusive javascript here.
There is an option in the LiveValidation library which is not explained in the documentation http://livevalidation.com/documentation
To prevent LiveValidation's submission while still keeping its validation events, you may use the "afterValidation" option.
Example:
var prevent = function (e) {
e.preventDefault();
};
var yourValidation = new LiveValidation(
"inputID", {
//Your other options
afterValidation: prevent
}
);
yourValidation.add( Validate.Presence, { your options } );
hi i check the blank field in the form and alert the user. but when alert the user it posts the data i couldnt return false not to refresh the page
$('#loginAccount').submit(function() {
$(this).find(':input:text').each(function(i) {
if($(this).val()=="") {
// alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
return false;
}
});
});
$('#loginAccount').submit(function() {
var valid = true;
$(this).find(':input:text').each(function(i) {
if($(this).val() == "") {
// alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
valid = false;
}
});
return valid;
});
You are currently returning from the each. What you need to do is track whether it's valid and then use that value as the return from your submit.
return false; takes on a different meaning inside of a jQuery each(). It is used to break out of the each. Maybe you could set a flag that is observed after the each() to see if the validation succeeded.
You need to return false in the submit function, not the each function:
$('#loginAccount').submit(function() {
var isValid = true;
$(this).find(':input:text').each(function(i) {
if($(this).val()=="")
{
isValid = false;
//alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
}
});
return isValid;
});
May be you shoul use closure to return a value?
$('#loginAccount').submit(function() {
var result = true;
$(this).find(':input:text')
.each(function(i) {
if($(this).val()=="")
{
//alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
result = false;
}
});
return result;
})