0

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" class="myclass" value="4">
<input type="number" class="myclass" value="2">
<input type="number" class="myclass" value="0"> <!-- "0" / blank, not counted -->
<input type="number" class="myclass" 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.

3
  • 1
    myclass should be class and not type, correct? In javascript you are not accesing the value property of any input. I think you should consider that. Commented Jul 7, 2022 at 22:36
  • @Carlos Sorry, I wrote it wrong, all that works but if there are zeros still counted, how to solve it? Commented Jul 7, 2022 at 22:42
  • are you sure it is not working? I tried it out and it works for me. jsfiddle.net/ghmvzLdc/2 Commented Jul 7, 2022 at 22:54

1 Answer 1

1

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" class="myclass" value="4">
<input type="number" class="myclass" value="2">
<input type="number" class="myclass" value="0"> <!-- "0" / blank, not counted -->
<input type="number" class="myclass" value="3">

<!-- count result = 3 -->
<div id="count"></div>

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

1 Comment

I will add onkeyup="livecountinput() because I want to make it live, if the input is changed then all counts will change live.

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.