views:

1282

answers:

6

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.

Thanks

+2  A: 
var junk=new Array();
junk.push('This is a string.');

Et cetera.

Jarett
+1  A: 

You can go with inserting data push, this is going to be doing in order

var arr = Array();
function arrAdd(value){
    arr.push(value);
}
andres descalzo
ok, got it. So I can get the contents of the array with a for loop and arr[counter]?
wonderer
+1  A: 

The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).

1:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

You could also pass an integer argument to control the array's size:

var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:

document.write(myCars[0]);

will result in the following output:

Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

myCars[0]="Opel";

Now, the following code line:

document.write(myCars[0]);

will result in the following output:

Opel
Chris
since the OP mentions the user entering a number of string, it sounds like he's talking about inputs
nickf
+1  A: 

As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.

var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9,10,11


var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9

You can even add elements like

var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30

you can even change the values

myArray[2] = 40


Printing Order

If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.

Page Submission

If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.

Manish Sinha
ok, so if I want to print the elements one at a time (say, the topmost) and the delete that from the array I would use document.writeln(myArray[0]) and once I am done I would call myArray.pop()? or pop() works from the last element?
wonderer
I would personally never advise you to print and delete elements of the array in the same loop. You should first traverse the array to print the elements. If you want to clear the array, no need to do array.pop() n number of times. Just set length property to 0 and its done!
Manish Sinha
+1  A: 

Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.

<script type="text/javascript">

var arr = [];

function add() {
   var inp = document.getElementById('num');
   arr.push(inp.value);
   inp.value = '';
}

function show() {
   var html = '';
   for (var i=0; i<arr.length; i++) {
      html += '<div>' + arr[i] + '</div>';
   }
   var con = document.getElementById('container');
   con.innerHTML = html;
}

</script>

<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
Guffa
great, thanks. Now, to show the elements of the array one at the time can I use a while loop?
wonderer
+1  A: 

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

nickf
thanks. I'm not using a prompt(), i think it's a bit annoying, however the second option looks good. How would I show one element at the time? Something like a input[0] then the user clicks a button and shows input[1], and so on...
wonderer
Ok, I've put the inputs one together now. http://jsbin.com/iyoge Click in the first input and then all you have to do is keep tabbing to the next one until you get bored.
nickf
great. I'm still trying to show ONLY one element at the time once I'm done entering them. Basically instead of showing the whole array ideally it would show arrayelemt[0], arrayelemt[1], arrayelemt[n] until i'm out of elements.
wonderer
I can't get to print one element at a time... any suggestions?
wonderer
one at a time? So when should the user be shown each subsequent one? after each click? after a set amount of time?
nickf