Walker Farrow Walker Farrow - 4 months ago 16
Javascript Question

How to get data attributes and values as object in select options (using chosen plugin)

I am using the chosen plugin (here) and I have a multiple select where I want to get the values returned as an object.

Here is the code:

<select class="chozen" id="entities" multiple>

<option data-name="Joe Blow" data-id="3" data-age="27">Joe Blow</option>
<option data-name="Trish Thompson" data-id="4" data-age="21">Trish Thompson </option>
<option data-name="Sam Jones" data-id="5" data-age="43">Sam Jones</option>

</select>


I then have a button to get the selected values of this input as:

var vals = $("#entities").val();

And it returns an array of innerHTML selected values as:

["Joe Blow","Trish Thompson","Sam Jones"]


(Note: if I set the "value" attribute, it will return the values as an array rather than the innerHTML)

What I am trying to do is take the data attributes and put that into an object array as:

[
{name:"Joe Blow",id:"3",age:"27"} ,
....
]


Does anybody have any suggestions? ....

I could not find anything on the chozen documentation.

Answer

Give this a try:

jQuery.fn.extend({
        selectedAsJSON: function(){
            var result = [];
            $('option:selected', this).each(function(){
                result.push($(this).data());
            })
            return result;
        }
    });

Usage:

$('#entities').selectedAsJSON();

The output will be an array of objects, where each data- will be a property.

Update: important to notice that this will work with any regular select element, not just with chosen. Also, your option may have any data- attr, will work as well.

Comments