user2062778
user2062778

Reputation: 39

What is the best way to access input in javascript?

function gener10k() {
  let x = getRndInteger(10000, 100);
  let x1 = getRndInteger(x, 10);
  let x2 = x - x1;
  let higherValue = numberToArray(x1);
  const longiness_higher = higherValue.length;
  let higherInput = document.getElementsByName("higher[]");
  for (var i = 0; i < longiness_higher; i++) {
    higherInput[i].value = higherValue[i].value;
  }
  alert('higherValue ' + x1 + ' ' + higherValue[0] + higherValue[1] + higherValue[2] + higherValue[3] + "higherInput " + higherInput[0] + higherInput[1].value + higherInput[2].value + higherInput[3].value);
}

function getRndInteger(max, min) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function getlength(number) {
  return number.toString().length;
}

function numberToArray(number) {
  let array = number.toString().split("");
  return array.map(x => parseInt(x));
}
<body>
  <div class="inputCoefs">
    <div class="inputCoef1">
      <input type="text" name="higher[]" class="coeficientsIn10000" />
      <input type="text" name="higher[]" class="coeficientsIn10000" />
      <input type="text" name="higher[]" class="coeficientsIn10000" />
      <input type="text" name="higher[]" class="coeficientsIn10000" />
      <input type="text" name="higher[]" class="coeficientsIn10000" />
    </div>
    <div class="output">
      <button class="but" id="checkit" onclick="gener10k();">DO IT</button>
    </div>
  </div>

I expected to write particular digits to equivalent input array. But instead, I have undefined variables. What is the best way to write to input from an array?

Upvotes: 2

Views: 56

Answers (1)

Jun Yu
Jun Yu

Reputation: 424

let higherInput = document.getElementsByName("higer[]");

This statement gets an object.

let higherValue = numberToArray(x1);

This statement gets a number array.

In your for loop:

higherInput[i].value = higherValue[i].value;

In this statement, higherInput[i].value refer to your text box value, but what's higherValue[i].value?
Just use higherValue[i].

You can use the statement below to see that higherValue[i] is a number.

console.log(typeof(higherValue[0]);

Upvotes: 1

Related Questions