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.
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.
-
1
What would
[(1, 2), (2, 3)]
end up creating exactly? – Andrew Whitaker 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. – Jack_of_All_Trades 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. – Andrew Whitaker 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. – epascarello Commented Jun 20, 2013 at 14:12
2 Answers
Reset to default 4JSON.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/NNcg7/
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]
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745074251a4609738.html
评论列表(0条)