wonderer wonderer - 2 months ago 10
Javascript Question

Javascript dynamic array of strings

Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.

Code is appreciated.

Answer

What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.

Ok, so you need some user input first? There's a couple of methods of how to do that.

  1. First is the prompt() function which displays a popup asking the user for some input.
    • Pros: easy. Cons: ugly, can't go back to edit easily.
  2. Second is using html <input type="text"> fields.
    • Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.

For the prompt method, collecting your strings is a doddle:

var input = []; // initialise an empty array
var temp = '';
do {
    temp = prompt("Enter a number. Press cancel or leave empty to finish.");
    if (temp === "" || temp === null) {
        break;
    } else {
        input.push(temp);  // the array will dynamically grow
    }
} while (1);

(Yeah it's not the prettiest loop, but it's late and I'm tired....)

The other method requires a bit more effort.

  1. Put a single input field on the page.
  2. Add an onfocus handler to it.
    1. Check if there is another input element after this one, and if there is, check if it's empty.
      • If there is, don't do anything.
      • Otherwise, create a new input, put it after this one and apply the same handler to the new input.
  3. When the user clicks OK, loop through all the <input>s on the page and store them into an array.

eg:

// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
    if (inputs[i].value.length) {
        input.push(inputs[i].value);
    }
}

After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:

var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
    div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);

I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge