25

I'm trying to validate a contact form and I want to create some sort of 'form completed' message once every input field has been filled in (some of the inputs are text boxes, some are radio buttons).

Here's my code so far:

$(document).ready(function() {
  $('.form:input').each(function() {
    if ($(this).val() != "") {
      $('.congrats').css("display", "block");
    }
  });
});
p.congrats {
  display: none;
}
<div class="form">
  <input type="text" />
  <br />
  <input type="text" />
</div>
<p class="congrats">Congrats!</p>

http://jsfiddle.net/7huEr/

mmmoustache
  • 2,273
  • 6
  • 41
  • 62

6 Answers6

40

This should get you started:

$(document).ready(function() {
    $(".form > :input").keyup(function() {
        var $emptyFields = $('.form :input').filter(function() {
            return $.trim(this.value) === "";
        });

        if (!$emptyFields.length) {
            console.log("form has been filled");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
    <input type="text" /><br />
    <input type="text" />
</div>
<p class="congrats"></p>
Jonathan
  • 2,700
  • 4
  • 23
  • 41
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 1
    Doing a `$('.form :input')` on every keyup event is not optimal. I would definitively cache that jQuery object: `var $fields = $( ':input', '.form' );` – Šime Vidas May 09 '12 at 13:51
  • @ŠimeVidas - yeah, I though someone would point that out. Fine, I'll fix it :) – karim79 May 09 '12 at 13:53
  • Also, of course, `$(document).ready(fn);` is history. We're doing `$(fn);` now. – Šime Vidas May 09 '12 at 13:54
  • @ŠimeVidas - Also true, but I still like the slightly more verbose and old-school version. – karim79 May 09 '12 at 13:56
  • Would this work if the browser caches and prepopulates the values on the form? It's looking for keyup... – riddle_me_this Jan 12 '16 at 15:03
  • This is not working for me for radio button and dropdown. I have used : var $fields = $('.profile-user-personal-form input[type="text"], .profile-user-personal-form input[type="radio"], .profile-user-personal-form select'); $fields.keyup(function() { var $emptyFields = $fields.filter(function() { // remove the $.trim if whitespace is counted as filled return $.trim(this.value) === ""; }); if (!$emptyFields.length) {alert("form has been filled"); } else { alert("uh-oh, you forgot to fill something out"); } }); – Nilesh Kumar May 06 '16 at 05:43
  • Why `$emptyFields` instead of `emptyFields`? – Dylan Czenski Jul 14 '16 at 14:27
6

try this :

$("#a").on('click',function () {
var bad=0;
 $('.form :text').each(function(){ 
        if( $.trim($(this).val()) == "" ) bad++; 
            
          
    });
    
    if (bad>0) $('.congrats').css("display","block").text(bad+' missing'); 
    else $('.congrats').hide(); 
});



 
   
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
    <input type="text" /><br />
    <input type="text" />
</div>
<p class="congrats"></p><input style="width:100px" value="check" id="a" type="button" />
Jonathan
  • 2,700
  • 4
  • 23
  • 41
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
5

This one uses jQuery's serializeArray function, so you don't have to worry about checking different types of fields or what qualifies as an empty field:

$.fn.isBlank = function() {
    var fields = $(this).serializeArray();

    for (var i = 0; i < fields.length; i++) {
        if (fields[i].value) {
            return false;
        }
    }

    return true;
};
Big McLargeHuge
  • 14,841
  • 10
  • 80
  • 108
3

$('#check').click(function () {
    var allFilled = true;
    
    $(':input:not(:button)').each(function(index, element) {
        if (element.value === '') {
            allFilled = false;
        }
    });
    
    console.log(allFilled);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
    <input type="text" /><br />
    <input type="text" />
</div>
<p class="congrats"></p>
<input type="button" id="check" value="check" />
Jonathan
  • 2,700
  • 4
  • 23
  • 41
jbabey
  • 45,965
  • 12
  • 71
  • 94
1

jsFiddle: http://jsfiddle.net/7huEr/38/

$(document).ready( function()
{
    // Iterate over each input element in the div
    $('.form input').each(function()
    {
        // Add event for when the input looses focus ( ie: was updated )
        $(this).blur( function()
        {
            // Variable if all inputs are valid
            var complete = true;

            // Iterate over each input element in div again
            $('.form input').each(function()
            {
                // If the input is not valid
                if ( !$(this).val() )
                {
                    // Set variable to not valid
                    complete = false;
                }
            });

            // If all variables are valid
            if ( complete == true )
            {
                // Show said congrats
                $('.congrats').show();
            }
        });
    });
});​
Jonathan Payne
  • 2,223
  • 13
  • 11
1

Modern Vanilla Solution:

// Returns True if all inputs are not empty
Array.from(document.querySelectorAll('#myform input')).every(
    function(el){return el.value;}
)
jeromej
  • 10,508
  • 2
  • 43
  • 62