Check to make sure all fields are filled Jquery - javascript

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..

Related

How to not validate certain inputs

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 &not 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;
}

Check whether the required field is not empty

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.

Check if input field is empty on fields with jQuery

I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.

check if all text inputs are empty

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');
}
});

Form validation does not happen

My form has some fields that are mandatory and I have marked them with class="required". I am writing the below jquery to validate this form, but it doesn't happen. I think either I am messing with calling the two functions or I am not getting the proper element through $(this).
<script type="text/javascript">
function validatemyForm() {
$('.required').each(function() {
if($(this).val() == "" || $(this).replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Filed</span>');
return false;
}
else {
$(this).remove();
}
})
return true;
}
</script>
I am calling the form, from the onsubmit event handler <form id="myform" onsubmit ="return validatemyForm();">. Am I incorrectly using each and this of jQuery?
A number of things:
You can use replace on a String, whilst you use it on a jQuery object. There is no $(this).replace. If you want to check for whitespace, you need the value, i.e. $(this).val().replace.
You use $(this).insertAfter which means that the input element is inserted after the span. $(this).remove simply removes the input element which isn't what you're after either I think.
You return false in the each(), but this doesn't return that value in the validatemyForm function. In that function, you always return true.
I changed it to this to get it working: http://jsfiddle.net/DaDQT/6/.
Your function validatemyForm always returns true. The return false you have in there is inside the function passed to each. validatemyFormdoes not stop at this point.
The following should work as you expect it (untested code):
<script type="text/javascript">
function validatemyForm() {
var ok = true;
$('.required').each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Field</span>');
ok = false;
}
else {
$(this).remove();
}
})
return ok;
}
</script>

Categories

Resources