Reputation: 243
I'm trying to create a html select array option like the following
<select name="tablename">
<option value="['one','two','three']">Option one</option>
</select>
in javascript
var myArray = new Array();
myArray[0] ="one";
myArray[1] ="two";
myArray[2] = "three";
option.value=myArray;
but when i try to get value from it using
var myArray2 = new Array();
myArray2 = $('select[name="tablename"]').val();
val=myArray2[0];
it did not return anything...anything went wrong
Upvotes: 0
Views: 3432
Reputation: 8220
I'm not sure what exactly you want to do, but if you want to store array ["one","two","three"]
into single OPTION
and then read this array from javascript, you can do next:
HTML:
<select name="tablename">
<!-- IMPORTANT COMMENT: use single quotes for value='' and double quoutes for values in array -->
<option value='["one","two","three"]'>Option one</option>
</select>
jQuery:
// reading array from OPTION
var myArray2 = jQuery.parseJSON($('select[name="tablename"]').val());
// myArray2 now is an javascript Array
console.info(myArray2);
UPDATE:
You can use native javascript JSON
object methods to convert Array into string and then store into html OPTION or SELECT value; or to convert value of OPTION or SELECT into Array (if you not need to support IE version less than 8):
// store Array into OPTION value
myOption.value = JSON.stringify(["one","two","three"]);
// read Array from SELECT value from your example
var newArray = JSON.parse($('select[name="tablename"]').val());
Read more aboute JSON.parse()
and JSON.stringify
in MSDN: http://msdn.microsoft.com/en-us/library/cc836458%28v=VS.94%29.aspx and in MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON
Upvotes: 1
Reputation: 2790
First, edit your markup.
<option value="[one,two,three]">Option one</option>
Get the value of option tag.
v = $('option').val();
'v' would be "[one,two,three]" in string object.
v = v.slice(1, -1);
then, it is "one, two, three" now split it,
yourArray = v.split(',');
finally you get yourArray ["one", "two", "three"]
:)
Upvotes: 0
Reputation: 16150
Option value can store string only. You can store array in some stringified form, and parse it in JS. Eg:
<select name="tablename">
<option value="['one','two','three']">Option one</option>
</select>
// JS
var myArray2;
myArray2 = $('select[name="tablename"]').val();
myArray2 = eval(myArray2);
alert(myArray2[0]);
Working demo: http://jsfiddle.net/kZape/
Upvotes: 2