Alex Rivera | Logout

code to set a select box option value as an object

Asked 2011-07-04T14:05:45.337
33

in an html page i have got, i have a select box like this with values.

<select onChange="return filler(this.value);">
<option value="{'name':'rajiv',age:'40'}">a</option>
<option value="{'name':'mithun',age:'22'}">f</option>
</select>

i want to pass a javascript array or object as the option value. right now it is treating the option value as a string.

i want it to be an array so that i can access it by

this.value.name,this.value.age in the filler function.

is this possible?

Edit
Report

2 Answers

37

You will not be able to store objects/arrays in the value attribute, however an option would be to use data-* attributes which supports json automatically with jQuery 1.4.3+

<select>
    <option data-value='{"name":"rajiv","age":"40"}'>a</option>
    <option data-value='{"name":"mithun","age":"22"}'>f</option>
</select>

And using .change()

$("select").change(function(){
    alert($(this).find(":selected").data("value").age);
});

Example on jsfiddle

answered 2011-07-04T14:15:11.200
6

You can use parseJSON to convert the string to an object when using it, but the value needs to be a string.

  var option = $('select').val();
  var selected = $.parseJSON(option);
  alert( selected.name + ': ' + selected.age );
answered 2011-07-04T14:12:42.840

Your Answer