Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count non-empty input field[]?

With jQuery how do I count how many fields of my array field[] are not empty ?

Sample of the input field

<input type="file" name="arquivo[]" id="arquivo">

I was trying to make something up using map and get but it is not coming along well:

var total = 0;
var count = $('#arquivo[value!=""]').map(function() { total = total+1; }).get();

But no matter how many fields I have filled it always end up with the value of 1 and if I have no fields filled 0.

like image 251
Prix Avatar asked May 20 '11 06:05

Prix


2 Answers

You can just find the length of the jQuery object, which returns the number of matched elements:

$('#arquivo[value!=""]').length

But you do know that this will always return 0 or 1? The id property is unique to only one element, so you can't reuse it multiple times.


For example:

<div id="foo"></div>
<div id="foo"></div>

When you run:

$('#foo').length;

It returns 1, because only one element should exist with the id of foo.


Now try this:

<div class="foo"></div>
<div class="foo"></div>

When you run:

$('.foo').length;

It returns 2. Why? Because class can be reused many times.


What are you trying to do? Can you post a scenario with multiple input fields?

like image 51
Blender Avatar answered Oct 25 '22 07:10

Blender


If you like to query and count by element name. You can use the below code

$('[name*=arquivo][value!=""]').length
like image 24
Bharath Avatar answered Oct 25 '22 08:10

Bharath