Reputation: 449
I am using the jquery select2 plugin for suggestive form fields. I am trying to access the data stored in my original hidden input fields data attribute. I need the data from these attributes so I can send them to a php script via Ajax. Does anyone have any suggestions on how this would be done? I cannot seem to find a answer on google or the official website.
Thanks
Upvotes: 1
Views: 6786
Reputation: 1724
Like in the docs:
//Template:
<select>
<option value="0" data-foo="bar">option one</option>
</select>
//Initiate select2
$("select").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
//access custom data
function format(state) {
var originalOption = state.element;
return $(originalOption).data('foo');
}
Upvotes: 2
Reputation: 11
We can get data attributes for the selected option
var seledted = $("#selectId").select2().find(":selected");
var s = $(seledted).data("data-field");
Upvotes: 1
Reputation: 161
You could also try the following. Suppose you have a select, you can add additional information to the options by using standard data-attribute syntax from jQuery, see jQuery data() API.
<select id="product">
<option value="prod_x" data-additional-info="1234X">Product X</option>
<option value="prod_y" data-additional-info="1234Y">Product Y</option>
</select>
Now in your javascript you can get to the option element itself by using .select2("data"), according to api docs - "Gets or sets the selection. Analogous to val method, but works with objects instead of ids". To get to the option object itself you have to go through the element, an array of all the selected options. In the example below the select is not multi value selectable so I always use the first object from the array, in addition to getting the object I wrap the result from ".element[0]" in $() to make it a jQuery object.
// Get the selected option using select2's api...
var selectedOption = $($("#product").select2("data").element[0]);
Now that we have a jQuery object we can use the jQuery data() API as follows to retrieve the arbitrary data stored on the option element.
var additionalInfo = selectedOption.data("additional-info");
The additional info variable will now contain either "1234X" or "1234Y" depending on which one was selected.
Using this you could eliminate the hidden inputs that holds the additional data and tie it directly to the selected option.
Upvotes: 2
Reputation: 449
I ended up accomplishing this by
$(".suggestive-entry").click(function() {
var val = $(this).siblings('input:hidden').attr('data-field');
alert(val);
});
as you can see i used the siblings attribute to get the hidden input closest to the select2 box that generated the click event.
Upvotes: 0