Home > Back-end >  count number of inputs which have value
count number of inputs which have value

Time:09-22

js noob here - I'm trying to count the number of inputs that have a value out of a calculated number of them. The code I came up with trying to achieve that is the following:

var fields = document.querySelectorAll('[id^=example-]'), count = 0;
for (var z = 0; z <= fields.length; z  ) {
    if (fields[z].value != "") {
        count = count   1;
    }
    console.log('count is: '   count);
}

Context: there are 3 inputs total and the above code executes on a click event.

Now the first time, this obviously runs fine if for example I set the value of the first input out of the three and returns [1]. The second time I update the same field's value, the counter increases again (logically).

Now, what I would like to achieve is to check all three inputs at the time the event fires & count how many of them have a value (and not increase the counter furthermore if they are already counted as having a value in the previous fire event).

Any help would be greatly appreciated. Thanks!

CodePudding user response:

Shorter

const count = [...document.querySelectorAll('[id^=example-]')]
  .filter(fld => fld.value.trim() !== "")
  .length
  • Related