JackFrost
JackFrost

Reputation: 113

How to apply an array through an input with type=text to a javascript variable?

I want to write an array like [1, 2, 3] into the text input on the html page and by clicking on the button apply it to the var array of the function called inputArray().
I tried to do so using

var array=document.querySelector("#inputNumber").value;

but that doesn't apply it as an array, just as a string I guess.
The other function called numbeRray(array) will then check if the array only consists of numbers.
Right now it checks if the single characters of the string are numbers because I wasn't able to add an array yet...

function numbeRray(array) {
  for (var a = 0; a < array.length; a++) {
    if (isNaN(array[a])) {
      throw new Error('The element in position ' + (a + 1) + ' of the array is not a number');
    }
  }
}

function inputArray() {
  var array=document.querySelector("#inputNumber").value;
  try {
    numbeRray(array);
  } catch (error) {
    alert(error.message);
    return;
  }
  alert(array);
}
<input type="text" id="inputNumber"/>

<button type="button" onclick="inputArray();">Check Array</button>

Upvotes: 0

Views: 1577

Answers (1)

vipcxj
vipcxj

Reputation: 1038

function numbeRray(array) {
  try {
    array = JSON.parse(array);
  } catch (e) {
    throw new Error("Invalid input.")
  }
  if (!Array.isArray(array)) {
    throw new Error("Not array.")
  }
  for (var a = 0; a < array.length; a++) {
    if (typeof array[a] !== 'number' || isNaN(array[a])) {
      throw new Error('Das Element an Position ' + (a + 1) + ' des Arrays ist keine Zahl');
    }
  }
}

function inputArray() {
  var array=document.querySelector("#inputNumber").value;
  try {
    numbeRray(array);
  } catch (error) {
    alert(error.message);
    return;
  }
  alert(array);
}
<!DOCTYPE html>
<html lang="de">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Fehlerbehandlung</title>
</head>

<body>
<input type="text" id="inputNumber"/>

<button type="button" onclick="inputArray();">Check Array</button>

  <script type="text/javascript" src="js/code6.js"></script>
</body>

</html>

Since the input is a json, Use JSON.parse to convert it to the array.

Upvotes: 1

Related Questions