Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 656
Walker Farrow Avatar asked Jul 25 '15 01:07

Walker Farrow


People also ask

How do I select an element with a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

What is a chosen attribute?

Definition and Usage. The selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.

How to remove chosen jQuery?

By default, pressing delete/backspace on multiple selects will remove a selected choice.


1 Answers

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.

like image 72
Andre Calil Avatar answered Sep 22 '22 19:09

Andre Calil