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.
Like all scripting languages, JavaScript has dynamic arrays: their size is not predetermined, nor the type of data.
There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.
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.
prompt()
function which displays a popup asking the user for some input. <input type="text">
fields. 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.
onfocus
handler to it. <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
var junk=new Array(); junk.push('This is a string.');
Et cetera.
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