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.
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'm trying to make an easy validator in jquery for my input fields.
Currently i got the following:
function checkInputs(){
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
And then i got a button right that is this:
$('#confirm').click(function () {
alert(checkInputs());
});
But this always returns true even if the input is empty.
Also after this works am going to make to where if all inputs are filled in, a button will be enabled to click on.
edited it so it has a selector now, still getting always true.
Thanks in advance
Try use the filter attribute to get the inputs that has a required attribute.
$('input').filter('[required]')
Added code to check if inputs are filled and enable or disable button. Note if we use this, there aint much point of the $('#confirm').click(function()); function since this button will only be enabled when the inputs are filled.
function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
$('#confirm').click(function() {
alert(checkInputs());
});
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})
checkInputs()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input required>
<input required>
<input required>
<button id="confirm">check</button>
</form>
Try to target the element in this way:
$('input[required]')
This should do the trick.
if it is 0 then all input filled otherwise it will return 0 mean any one or more are empty input.
function checkInputs(){
var flag = 0;
$('input').each(function() {
if($(this).val() == ''){
return flag = 1;
}
});
return flag;
}
$('#confirm').click(function () {
alert(checkInputs());
});
Your selector is looking for a tagName <input-required></input-required> that obviously doesn't exist.
Add a dot prefix for class
Can also use filter() to simplify
function checkInputs(){
return !$('.input-required').filter(function() {
return !this.value;
}).length;
}
NOTE: Will not work on radios or checkbox if those are part of the collection of elements with that class and you would need to add conditional for type if that is the case
You forgot to put class symbol in jQuery:
function checkInputs() {
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
Try this..
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;
}
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');
}
});
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;
})