Select2 set the selected value to a hidden field

I have a select2 function as shown below

function select2AutocompleteManyToManyField(field, request_url){ var map = {}; $("#"+field).select2({ multiple: true, placeholder: field, minimumInputLength: 3, ajax: { // instead of writing the function to execute the request we use Select2 convenient helper url: request_url, dataType: 'json', data: function (term) { return { query: term }; }, results: function (data) { // parse the results into the format expected by Select2. var objects = []; $.each(data,function(i,obj){ map[obj.translations__name] = obj; objects.push({ "text": obj.translations__name, 'id': map[obj.translations__name].id }); }); return {results: objects}; } } }); } 

I want to update another value of a hidden field with selected field identifiers. Is there any way to do this?

+4
source share
2 answers

I went through this and could not find a solution. then I worked as shown below on you sunbmit click fill in the hidden field

  $("#mysubmit").click(function () { $('#Hiddenfields').val($('#divforselect').val()); }); 
+3
source

Here is how I saw here and successfully applied:

  /* bind select2 */ var select2 = $( '#city' ).select2({ initSelection : function( element, callback ) { var data = { id: element.val(), text: element.val() }; callback(data); }, minimumInputLength: 2, ajax: { url: "/city", dataType: 'jsonp', data: function( term, page ){ return { q: term, page_limit: 10 }; }, results: function( data, page ){ return { results: data.content.result }; } }, }).data( 'select2' ); select2.onSelect = ( function( fn ){ return function( data, options ){ $( '#city_id' ).val( data.id ); return fn.apply( this, arguments ) }; })( select2.onSelect ); 
+2
source

Source: https://habr.com/ru/post/1479517/


All Articles