Erik
Erik

Reputation: 5791

Counting the number of input's and textarea's with data

I have a script that only works in jquery 1.7.2. I'm also getting a lot of conflicts with this script.

Is there an alternative to this approach? I'm trying to count the number of input's and textarea's that have data typed inside them. I just need a number.

Here is my current script:

$('#form_register').on('keyup', function() {
var number = $('#form_register').find('input, textarea')
// filter out every empty input/textarea
.filter(function() {
    return $(this).val() != '';
}).length;
$('.inputCount').val('There are ' + number + ' empty input fields');
console.log('test');
});​

Upvotes: 2

Views: 413

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

I'd use the change handler too, to prevent someone paste the text inside a field.

EDIT :
To count upwards as you asked in your comment:

jsBin demo

$('#form_register').on('keyup change', function() {
    var number = 0;
    $(this).find('input, textarea').each(function(){
       if( this.value !== ''){
          $('.input_count').val(number++);
       }
    });       
});

To redo to count downwards (DEMO) just use === and exclude the print from the each function:

       if( this.value === ''){
          number++;
       }
       $('.input_count').val(number);

If you have more issues, try to wrap the code into:

(function($){ // remap '$' to jQuery
 
    // CODE HERE

})(jQuery);

Upvotes: 1

Related Questions