I want to count the input after it is filled with numbers, but if it is not filled then the input is not counted.
I tried using the following HTML
<input type="number" value="4">
<input type="number" value="2">
<input type="number" value="0"> <!-- "0" / blank, not counted -->
<input type="number" value="3">
<!-- count result = 3 -->
<div id="count"></div>
and javascript
function livecountinput(){
let num = document.getElementsByClassName('myclass').length;
let count = document.getElementById('count');
count.innerHTML = num
};
document.addEventListener("DOMContentLoaded", function(event) {
livecountinput();
});
all that works but if there are zeros still counted, how to solve it? Any help would be appreciated.
CodePudding user response:
With document.getElementsByClassName('myclass').length
you get the length of the array with HTMLNodes. If you have 4 elements with that class name then you get a length of 4. Maybe this is what you want:
function livecountinput() {
let numNodes = document.getElementsByClassName('myclass');
let length = [...numNodes].filter((node) => parseInt(node.value) !== 0).length
let count = document.getElementById('count');
count.innerHTML = length
};
document.addEventListener("DOMContentLoaded", function(event) {
livecountinput();
});
<input type="number" value="4">
<input type="number" value="2">
<input type="number" value="0"> <!-- "0" / blank, not counted -->
<input type="number" value="3">
<!-- count result = 3 -->
<div id="count"></div>