2

Is it possible to have a input field where user can input the array and the function which it passes the value treats it as an array? To be clear, is this possible using javascript and HTML?

<input....of some type....>

function (from input as a form of array){

calculation
}

I would like to have an input field where I can input something like [1,2,3,4..] or [(1,2),(2,3)...] and pass that to the function without any further manipulation, hoping that it will treat the array as array not as 'text'. I think I can use eval but I don't want to trust the user.

4
  • 1
    What would [(1, 2), (2, 3)] end up creating exactly? Commented Jun 20, 2013 at 14:09
  • @AndrewWhitaker:it is something from python I cannot forget.nothing, I know in javascript it creates...just used it for illustration. Commented Jun 20, 2013 at 14:10
  • That won't do what you expect it to in JavaScript. You could use JSON.parse for the simple array though. Commented Jun 20, 2013 at 14:12
  • JSON.parse would help, or if that is not available, either a simple split(",") and a mapping to turn strings into numbers or you need to use a regular expression to get multi-dimensional arrays. Commented Jun 20, 2013 at 14:12

2 Answers 2

4

JSON.parse() will help out here

Support is IE8+

HTML:

<input type="text" id="t1" value="[1,2,3,4,5,6]"/>
<input type="text" id="t2" value="[[1,2],[3,4],[5,6]]"/>

JavaScript:

var a1 = JSON.parse(document.getElementById("t1").value);
var a2 = JSON.parse(document.getElementById("t2").value);
console.log(a1);
console.log(a2);

Fiddle

http://jsfiddle.net/NNcg7/

Sign up to request clarification or add additional context in comments.

1 Comment

I think your caps lock is stuck.
1

You can create an array from the text input if the data is entered with a standard delimiter. Meaning, if the user inputs 1,2,3,4 into the text field, you can create an array in Javascript using the split method.

var myInputValue = document.getElementById(yourElementId); //value will be "1,2,3,4"
var myArray = myInputValue.split(","); //value will be [1,2,3,4]

1 Comment

Problem with split is the indexes are filled with strings and not numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.