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!
}
}
});
Related
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();
}
});
I try to validate the textbox by mouse out in jquery, my code is running by any mouse out means it shows Enter valid Email. several times, any time that I click outside the textbox.
This is my code:
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
my code is not working when it is outside the document.ready.
This is what I get when I run by each time I click:
$(this).after('<div class="Required">Enter valid Email.</div>');
this will add a new after every focus out of the input box.
Instead have a placeholder div below the text box.
<div id="emailErrorMsg"></div>
and do
$('#emailErrorMsg').html('Enter valid Email.');
this will also let you add more error messages.
Remove the div before you add one to prevent repeats.
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
if($(this).next().hasClass('Required'))
$(this).next().remove();
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
I have implemented some code to validate text box and insert error div after the element if entered value is not valid.
I hope below code will solve your problem
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
var errorLabel = errorsFor(this);
$(this).addClass('ChangetoYellow');
if(errorLabel.length > 0){
$(errorLabel).show();
}
else {
$(this).after('<div for='+ this.name +' class="required">Enter valid Email.</div>');
}
return false;
} else {
$(this).next(".required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
function errorsFor( element ) {
var name = idOrName(element);
return $('.required').filter(function() {
return $(this).attr("for") === name;
});
};
function idOrName( element ) {
return element.name ? element.name : element.id || element.name;
};
});
Test sample code
Try This one first remove previous error messages and add it.
JS
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).parent().find(".Required").remove();
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).parent().find(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
For Simple Example Fiddle (if u want add the regular expression and test it) -
http://jsbin.com/pujemay/edit?html,js,output
I want to check whether the required field is empty or not.
I used the code below.
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "")
alert("Empty Fields!!");
}
});
But it was alert more than one time.
JSFiddle:
http://jsfiddle.net/hbk2a5qo/3/
Why not directly use required attribute in HTML:
<input id="name"type="text" data-label="required" required/>
You need to use a flag
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault()
AlertSave();
});
});
function AlertSave() {
//use the flag to set the valid status in the loop
var valid = true;
//iterate over only the required elements
$(':input[data-label="required"]').each(function () {
if ($(this).val() === "") {
valid = false;
return false;
}
});
if (valid) {
//do your save
} else {
alert("Empty Fields!!");
}
}
Demo: Fiddle
As you have used $(":input").each() so it will go through all fields. But you can use flag to show alert only once.
function AlertSave() {
var alertShown=false;
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "" && !alertShown)
{
alertShown=true;
alert("Empty Fields!!");
}
}
});
}
You Updated Fiddle
By using required attribute (which is recommended), this will return all the required input fields that has no value:
var inputsWithMissingValues = $('input[required]').filter(function(i, input) {
return !input.value.length;
});
So, if the length of that is more than zero, then you have required fields with missing value.
is it possible to do this automatically. mean when i type text and click on the second textfield autocheck the first one. then when both ok show the div2 and so on.
here is some code
var step1 = function() {
var first = $("#f_name").val();
var last = $("#l_name").val();
var error = false;
if (first == "") {
$("#f_name").next().text("*ErrorMsg");
error = true;
} else {
$("#f_name").next().text("");
}
if (last == "") {
$("#l_name").next().text("*ErrorMsg");
error = true;
} else {
$("#l_name").next().text("");
}
if (error == false) {
$("#send").submit();
$('#div1').show('slow');
} else {
returnfalse;
}
}
var step2 = function() {
var email1 = $("#e_mail").val();
var adress1 = $("#adress").val();
var error2 = false;
if (email1 == "") {
$("#e_mail").next().text("*ErrorMsg");
error2 = true;
} else {
$("#e_mail").next().text("");
}
if (adress1 == "") {
$("#adress").next().text("*ErrorMsg");
error2 = true;
} else {
$("#adress").next().text("");
}
if (error2 == false) {
$("#send2").submit();
$('#div2').show('slow');
} else {
returnfalse;
}
}
$(document).ready(function() {
$('#div1').hide();
$('#div2').hide();
$("#send").click(step1);
$("#send2").click(step2);
});
hope anyone can help me. and sorry for my bad english :)
greatings
The way that I would do it is:
Assign a variable, something like numSteps and set its initial value to 1
onFocus and onBlur, run a function that steps through each field, based on numSteps
If any fields are empty (or however you want to validate them), set error = true
if !error numSteps++
Make all elements up to numSteps visible
Hope this helps
Very crude example, but demonstrates what I was referring to:
http://jsfiddle.net/aSRaN/
I want to check if all text inputs with class 'textinput' are empty, but it only seems to check if the first input is empty or not, I can't figure out why. can anyone see what I'm doing wrong?
$('#check').click(function(){
var allEmpty;
$('.textinput').each(function(){
if(!$('.textinput').val()){
allEmpty = true;
}
});
if (allEmpty == true){
alert('all empty');
}
});
Find all .textinput that are not empty, and check the selector length. If none exist, they are all empty :
$('#check').on('click', function(){
var allEmpty = ! $('.textinput').filter(function() {
return $.trim( this.value ) != "";
}).length;
if (allEmpty) alert('all empty');
});
or
if ( ! $('.textinput[value !=""]').length ) alert('all empty');
Try checking against the opposite logic. If any of the values are set, then they're not all empty.
Also, you want to make use of $(this) when you're within the context of the .each() function. Otherwise, calling $('.textinput') will re-select those elements again rather than working on the current one.
Adding $.trim() ensures that whitespace is not counted as an actual value, but you can remove this if you want to count whitespace as a value.
$('#check').click(function() {
var allEmpty = true;
$('.textinput').each(function(){
if ($.trim($(this).val())) {
allEmpty = false;
}
});
if (allEmpty == true){
alert('all empty');
}
});
Your condition is wrong; you are setting allEmpty = true for each single item.
You have to invert your logic:
$('#check').click(function(){
var almostOneNotEmpty = false;
$('.textinput').each(function(){
if($(this).val()){
almostOneNotEmpty = true;
}
});
if (!almostOneNotEmpty == true){
alert('all empty');
}
});
this should be your condition >>
if(!$('.textinput').val()){
}else {
allEmpty = true;
}
This simple check will tell you if they are all empty:
var isEmpty = !$('.textinput').map(function() { return this.value; }).get().join('');
This will give you boolean true if all the fields are blank.
You need to use the element that is selected by the each method by using "this".
$('#check').click(function () {
var allEmpty;
$('.textinput').each(function () {
if (!$(this).val()) {
allEmpty = true;
}
});
if (allEmpty == true) {
alert('all empty');
}
});