I would like to do two things:
-
I want to count the number of
inputs
that have a value. (doesn’t matter if the value is A or X). -
Then, count the number of
inputs
whose value is equal to A
therefore, the results should contain 6 of 14 items
This is what I tried to count the inputs that already have value:
var filledInputs = $(".col input").filter(function() {
return !!this.value;
}).length;
const test2 = document.querySelectorAll(".result");
test2.forEach((item) => {
item.innerHTML = filledInputs;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div class="col">
<input type="text" value="A">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="A">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text" value="X">
<input type="text" value="X">
<input type="text" value="A">
</div>
<div class="col">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="results"></div>
8
Answers
One possible implementation with jQuery:
Use the same logic that you made to find the filled inputs, to find the inputs with value
A
Perhaps you meant this:
Here’s a minimal solution:
Full snippet:
Maybe the easiest method (and marginally more performant than filtering) in vanilla JS is to do three selections: one on all inputs, and then two selections using the value attribute.
If you want updated counts while you are filling in the fields you could recalculate it in an event driven function: