Search code examples
jquerydrop-down-menuextend

Put a json object in Dropdownlist value property, how to access it


I'm putting a json object into the value of a dropdownlist / option

<select>
    <option value="{a:'1',b:'11'}">a</option>
    <option value="{a:'2',b:'12'}">b<option>
    <option value="">c</option>
    <option value="">d</option>
</select>

How can I access the value of the selected item?

var s = {};
$('select').change(function(){
    s = $(this).val();
    alert (s.a);
});

http://jsfiddle.net/uzCm9/


Solution

  • First, you should get in the habit of caching values, because doing the $() thing constantly will take a toll on your performance.

    That's not to say that it's important, here. But it's something that the Twitter people learned the hard way, more than once.

    When you're dealing with a lot of results, or you're dealing with a lot of changes, save the list of items to a variable, or save the element that you want to work with.

    Anyway...

    var json = $(this).value, obj = $.parseJSON(json);

    do_awesome_thing(obj.a);