M.Saeed
M.Saeed

Reputation: 303

how to measure the number of entry with input value in HTML

I am learning JS and HTML and have three text inputs need to enter any value of number and then if I enter any number need to measure as a single value "1", for example: if I filled two input values will measure 2 and if I entered 3 input values will measure 3.

I made it with this way but need to shorten it and don't know how to do it!

    <!DOCTYPE html>
<html>
<body>

<h2>JavaScript Can Validate Input</h2>

<p>Please input a number</p>

<input id="numb1" value="">
<input id="numb2" value="">
<input id="numb3" value="">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x1, text, y, z1, n, x2, x3, z2, z3;

  // Get the value of the input field with id="numb"
  x1 = document.getElementById("numb1").value;
  x2 = document.getElementById("numb2").value;
  x3 = document.getElementById("numb3").value;

  // only measure if only has number.

  if (isNaN(x1)) {

  } else {
    y=0;
    z1 = y+1;
  }
    if (isNaN(x2)) {

  } else {
    y=0;
    z2 = y+1;
  }
    if (isNaN(x3)) {

  } else {
    y=0;
    z3 = y+1;
  }
  document.getElementById("demo").innerHTML = z1+z2+z3;
}
</script>

</body>
</html> 

Any help for that, please!

Upvotes: 1

Views: 99

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

Consider the input element names as an array, map() them to the input element values, and reduce() them to the total number that have a numeric value set:

function myFunction() {
  const inputs = ['numb1', 'numb2', 'numb3'];
  const z = inputs.map(v => document.getElementById(v).value)
                  .reduce((a, v) => a + (v && !isNaN(v)), 0);
  document.getElementById("demo").innerHTML = z;
}
<h2>JavaScript Can Validate Input</h2>

<p>Please input a number</p>

<input id="numb1" value="">
<input id="numb2" value="">
<input id="numb3" value="">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

Upvotes: 2

Related Questions