Timo Timo - 11 months ago 61
CoffeeScript Question

jQuery: Check If All Form-Fields Are Populated

I am using jQuery + CoffeeScript + Pug (+ Bootstrap 4):

I have a

, which looks like this, but with many (ten or more) items, so individually checking them is hard:


label Title
input.form-control(name="title" type="text")

label Description


I'd like to check if all
fields are populated, each time the user types something. The goal is to decide whether a
-button should be shown or hidden. This
-button should only be shown when the
is fully populated.

My first attempt was:

$(window).on 'keydown', (keydown) ->

I tried to to apply jQuery's
loop, then I tried to use jQuery's
-method. But I didn't come to a solution. Maybe you can help.

Thank you.

Edit 2:

formElements = $ 'form input[type="text"], form input[type="number"], form textarea'

formFilled = ->
filled = true
formElements.each ->
if $(this).val().length is 0
filled = false

formElements.on 'keyup', (keyup) ->
if formFilled()

Somebody who knows what the coffee-script compiler makes of this ??

Answer Source

First off, don't use $(window).on('keydown'), simply because that will trigger any time the user presses a key, regardless of where on the screen they are. You'll want to narrow it down to form inputs.

If the form is entirely text fields and text areas, you can do this:

//Function will return a true or false
function formIsComplete() {

    var isComplete = true;

    //For every text input and textarea in the form
    $('form input[type="text"], form textarea').each(function() {
        $t = $(this);
        if ($t.val().length == 0) {
            //Found an empty input
            isComplete = false;
            return false;

    //No empty inputs found
    return isComplete;

$(document).ready(function() {

    $saveBtn = $('#save');

    //Add 'keyup' event to all form text inputs and textareas
    $('form input[type="text"], form textarea').on('keyup', function() {
        if (formIsComplete()) {
            //All fields have values
        } else {
            //Something was empty

NOTE: I've changed the event from keydown to keyup, only because keydown triggers before the value of the input is changed. This means that when a user enters the first character, the keydown event will still see the input as empty.