Created
August 26, 2018 00:10
-
-
Save aguileraq/df36380417d3ef29f0263932d6cab9b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
function select2Action(id_selector,max_selection,placeholder,multiple) { | |
var arr = []; | |
$(`#${id_selector}`).select2({ | |
maximumSelectionLength: max_selection, | |
language: "es", | |
placeholder: placeholder, | |
width: '100%', | |
minimumInputLength: 3, | |
allowClear: true, | |
multiple: multiple , | |
ajax: { | |
url: URL, | |
dataType: "json", | |
type: "GET", | |
data: function (params) { | |
var queryParameters = { | |
q: params.term | |
} | |
return queryParameters; | |
}, | |
processResults: function (data, params) { | |
return { | |
results: $.map(data, function (item) { | |
console.log(item); | |
return { | |
text: item.name, | |
vid: item.source+item.id,//¿concatenar id y source? | |
source: item.source, | |
id : item.id | |
} | |
}) | |
}; | |
}, | |
cache: true | |
}, | |
templateSelection: function(container) { | |
//.attr( { title:"Test", alt:"Test2" } ); | |
$(container.element).attr( {'id': container.vid,'data-type':container.source, 'data-id':container.id }); | |
return container.text; | |
} | |
}).on('change', function (e) { | |
}).on('select', function (e) { | |
console.log("select"); | |
}).on("select2:select",function (e) { | |
//CUANDO SELECCIONAMOS UN ITEM, SE CREA EL ARRAY. | |
arr.push({ | |
type : e.params.data.source, | |
id : e.params.data.id | |
}); | |
$("#arr_ids").val(JSON.stringify(arr)); | |
}).on("select2:unselect",function (e) { | |
//AL MOMENTO DE ELIMINAR UN ITEM DEL SELECT, ELIMINAMOS ESTE OBJETO DEL ARRAY. | |
//console.log(e.params.data.source+" "+e.params.data.key); | |
//var $id = e.params.data.key; | |
var $id = e.params.data.id; | |
var $type = e.params.data.source; | |
console.log(e); | |
console.log(arr.length); | |
//remove option by id | |
//$("#"+$type+$id).remove(); | |
$("#"+$id).remove(); | |
var position = -1; | |
for (var i = 0; i < arr.length; i++) { | |
if (arr[i].type === $type && arr[i].id === $id) { | |
position = i; | |
break; | |
} | |
} | |
arr.splice(position, 1); | |
$("#arr_ids").val(JSON.stringify(arr)); | |
console.log(arr); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment