Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value to an array

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?

like image 299
J. Doe Foe Avatar asked Mar 14 '26 17:03

J. Doe Foe


1 Answers

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" />
like image 60
Paul Fitzgerald Avatar answered Mar 17 '26 06:03

Paul Fitzgerald