Create a function to count numbers between two given numbers in JavaScript

Count the number of values between 2 user input values with an array

Create a function with login and execute only one button click. Get the inputs with getElementById and store the values given by the user inside num1 and num2 variables.

HTML Example code:-

<!DOCTYPE html>
<html> 
<body>
    <input type="text" id="num1">
    <input type="text" id="num2">
    <button onclick="GetNumCount()" type="button">search</button>

    <script type="text/javascript">
        function GetNumCount() {
          var total = 0;
          var num1 = document.getElementById('num1').value;
          var num2 = document.getElementById('num2').value;
          var array = [1, 4, 6, 7, 8, 6];

          for (var a = 0; a < array.length; a++) {
            if (array[a] >= num1 && array[a] <= num2) {
              total++;
          }
          
      }
      alert("Total numbers of values = " + total);
  }
</script>

</body>
</html>

Output:

Count number of values between 2 input values with array JavaScript

Create a function to count numbers between two given numbers in JavaScript

<script type="text/javascript">
        function GetNumCount() {
          var total = 0;
          var num1 = 1;
          var num2 = 10;
          var array = [1, 4, 6, 7, 8, 6];

          for (var a = 0; a < array.length; a++) {
            if (array[a] >= num1 && array[a] <= num2) {
              total++;
          }

      }

Do comment if you have any doubts and suggestion on this code and examples.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.