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>
1,2,3or 1 2 3`, or what?JSON.parse(val)after you get the value from the inputparseInt()on each part, then.push()it into the array. That's one way. ... A quicker way, would be toeval()it (though probably not recommended unless you sanitize the string first).[1,2,3]is a valid input value forJSON.parse