9

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.

2 Answers 2

18

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?

Sign up to request clarification or add additional context in comments.

6 Comments

@Blender yours and mine only count 1 and not all fields from arquivo[]
We receive multiple images up to 10 and the first 3 are required.
You might be using the id attribute incorrectly. Can you post the HTML with the 10 images?
@Blender arquivo[0], arquivo[1] ... arquivo[9]
Okay. You can't have two elements with the same id. Ever. The maximum is one, which is what jQuery returns correctly. Try using class instead of id (see my example).
|
3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.