javascript - Select2 custom read custom data attributes -


i using jquery select2 plugin suggestive form fields. trying access data stored in original hidden input fields data attribute. need data these attributes can send them php script via ajax. have suggestions on how done? cannot seem find answer on google or official website.

thanks

you try following. suppose have select, can add additional information options using standard data-attribute syntax 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 javascript can option element using .select2("data"), according api docs - "gets or sets selection. analogous val method, works objects instead of ids". option object have go through element, array of selected options. in example below select not multi value selectable use first object array, in addition getting object wrap result ".element[0]" in $() make jquery object.

 // selected option using select2's api...  var selectedoption = $($("#product").select2("data").element[0]); 

now have jquery object can use jquery data() api follows retrieve arbitrary data stored on option element.

 var additionalinfo = selectedoption.data("additional-info"); 

the additional info variable contain either "1234x" or "1234y" depending on 1 selected.

using eliminate hidden inputs holds additional data , tie directly selected option.


Comments