0

I need to check all the inputs to see if they are filled, in which case the submit button would become pressable and the user can submit their data safely:

unfilled = false;
$('.add-field').keypress(function(){
    $('.add-field').each(function(){
        if($(this).val() === ''){
            unfilled = true;
        } else {
            unfilled = false;
        }
    })
    console.log(unfilled);
});

This code works, but it has a strange twist; as the last empty input gains a character, it still returns true. If an input gains another character, only then it will return false. I am confused by this, as I understand that the .each() function is fired after a character has been added and the value of the input has been updated. Consequently, I do not see why it does not register that value.

styke
  • 2,116
  • 2
  • 23
  • 51
  • 1
    How come you feel the need to check every `add-field` when changing just one of them? Why not just check itself? The others would also just check themselves. – h2ooooooo Jun 27 '13 at 11:34

4 Answers4

2

You should set unfilled to false before entering the loop (but INSIDE the keyup).

In the loop you should only set unfilled to true when a field is emty and not set it to false again, otherwise you'll only know if the last field is filled in.

gitaarik
  • 42,736
  • 12
  • 98
  • 105
  • the code in the question still sets `unfilled` to `false` inside the loop – gitaarik Jun 27 '13 at 11:44
  • oh, wait, you removed the loop.. now i don't follow anymore :P – gitaarik Jun 27 '13 at 11:45
  • I am sorry, I am updating it as I go. I thought I didn't need the loop. Upon further investigation I do. Here is a JSfiddle http://jsfiddle.net/UzP4s/ – styke Jun 27 '13 at 11:48
  • Unfortunately setting `unfilled` to `false` before entering the loop does not work. – styke Jun 27 '13 at 11:50
  • You should set `unfilled` to false before the loop, but inside the `keyup`! Otherwise `unfilled` will always be true after the first time the loop ran and there was a missing value. – gitaarik Jun 27 '13 at 11:58
1

You could use filter and use keyup event instead for del keys:

DEMO

$('.add-field').keyup(function () {
    var unfilled = !! $('.add-field').filter(function () {
        return $.trim(this.value) === ""
    }).length;
    console.log(unfilled);
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

Here === means it is matching exactly the data types:

if($(this).val() === ''){

Replace it with == :

 if($(this).val() == ''){
Tomás
  • 3,501
  • 3
  • 21
  • 38
Moeed Farooqui
  • 3,604
  • 1
  • 18
  • 23
0

As far as I know, this is an 'issue' when using the KeyPress-event, because the Browser's UI Thread did not update the input field's value yet. Therefore the value currently is still 'empty' and thus true is returned; you can either use the KeyUp-event or try something like this: JavaScript keypress event get end value of textarea

Community
  • 1
  • 1
KilZone
  • 1,580
  • 9
  • 20