I'm very new in coding, so be patient please. I've made an array that looks like this:
var minArray = ["Hello", "Hi", "Yes", "No", "Good"];
function printit(number) {
document.getElementById('test').innerHTML = minArray[number];
}
<form name="f1">
<input type="text" value="" id="number" />
<input type="button" value="Word is:" onclick="printit(number)" />
</form>
<br/>
<div id="test" />
And I'd like to write in a number in the text field and then get that specific word from the array. So if I were to write 1 and then press print, the outcome would be: Hi.
Anyone that can nudge me in the right direction?
You are not getting the value of the input correctly. You have two options, both documented below.
To get the value of the input you need to do the following:
document.getElementById('number').value;
You also called your array myArray and minArray.
See full code example below.
var minArray = ["Hello", "Hi", "Yes", "No", "Good"];
function printit() {
const number = document.getElementById('number').value;
document.getElementById('test').innerHTML = minArray[number];
}
<form name="f1">
<input type="text" id="number" />
<input type="button" value="Word is:" onclick="printit()" />
</form>
</br>
<div id="test" />
You could also pass the event to the input onclick function and get the value from this. You will also have to convert the string to an integer using parseInt.
var minArray = ["Hello", "Hi", "Yes", "No", "Good"];
function printit(event) {
document.getElementById('test').innerHTML = minArray[parseInt(number.value)];
}
<form name="f1">
<input type="text" id="number" />
<input type="button" value="Word is:" onclick="printit(event)" />
</form>
</br>
<div id="test" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With