Extra data with initial value (ajax select2)

267 views
Skip to first unread message

Chris

unread,
Feb 8, 2017, 1:48:34 PM2/8/17
to select2
I have an ajax select2 box that works well. When an ajax query is made, the server returns some extra data. eg.

[
{id: 5, text: "My Text Here", extra_field: "Extra Value"}
]


When I want to set an initial value, how do I get that extra_field data in there? A regular option tag.
eg.
<select>
<option value="5" selected>My Text Here</option>
</select>

works for the value/text, but I can't figure out how to get the extra_field in there so I can reference it later. I'm hoping there's an easy way to do this (eg. data tags, or somehow passing in a json hash as the selected value instead of option tags).

Thanks for any help/advice!

Chris

unread,
Feb 8, 2017, 5:43:33 PM2/8/17
to select2
It seems one way is to have two arrays - one that you pass in as the 'data' argument when initializing the select2, and then the other you can use to set the selected value (as per this answer: http://stackoverflow.com/a/38141552 ).

Electric Bikes Backlinks

unread,
Jan 11, 2026, 7:36:45 AM (3 days ago) Jan 11
to select2
When setting an initial value in Select2, you can include extra data like 'extra_field' by passing a data object instead of just plain option tags. This way, the additional data is stored with the selected item and can be accessed later, making technology makes it easier to work with custom data fields in your Select2 dropdown.
Reply all
Reply to author
Forward
0 new messages