Timo Timo - 23 days ago 10
CoffeeScript Question

jQuery: Check If All Form-Fields Are Populated

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

I have a

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

form(method="post")

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

.form-group
label Description
textarea.form-control(name="description")

...


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

My first attempt was:

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


I tried to to apply jQuery's
each
loop, then I tried to use jQuery's
.val()
-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
filled

formElements.on 'keyup', (keyup) ->
keyup.preventDefault()
if formFilled()
save.show()
else
save.hide()


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

Answer

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
            $saveBtn.show();
        } else {
            //Something was empty
            $saveBtn.hide();
        }
    });
});

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.