My goal is to create an array, and when a button is clicked, it goes through each individual item of the array and alerts whether it's a number or not.
<body>
<form id = "form">
<p id = "instruction">Enter all values in the textbox, separated by a space.</p>
<textarea id = "textarea" rows = "8" columns = "60"></textarea>
<input id = "submit" type = "submit" value = "Sort Alphabetically" onclick = "stringSplitAlpha();">
<p id = "p"></p>
</form>
<script>
function stringSplitAlpha() {
var str = document.getElementById("textarea").value;
var arr1 = str.split(" ");
for (var i = 0; i < arr1.length; i++) {
window.alert(isNaN(arr1[i]));
if (isNaN(arr1[i]) == 'true') {
window.alert(arr1[i] + "is not a number.");
} else {
window.alert("arr1[i] + "is a number.");
}
}
}
</script>
</body>
When I run the code, everything works fine at the beginning. I put in some values in the textbox for the array, and when I click the button, window.alert(isNaN(arr1[i])); shows "true" on a letter and "false" on a number. This is expected.
However, when it says "true" for a letter, the next alert shows "... is a number." This comes from
if (isNaN(arr1[i]) == 'true') {
window.alert(arr1[i] + "is not a number.");
} else {
window.alert("arr1[i] + "is a number.");
}
, but is totally unexpected. window.alert(isNaN(arr1[i])); came up as "true" so shouldn't it say "... is not a number"? I was stumped here. I thought maybe there was some sort of syntax error, but there doesn't seem to be any. I tried both double and triple equal signs, to no avail.
Just to clarify, if I put in "1 34 hello" in the textbox, this is what would show up in the alerts, in order:
"false," "1 is a number," "false," "34 is a number," "true," "hello is a number". Only the last alert of "hello is a number" is incorrect.
Thanks in advance.