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.
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.
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.
By default, pressing delete/backspace on multiple selects will remove a selected choice.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With