Como manipular un elemento seleccionado en select2

publicado por: Anonymous

Tengo este código y me gustaría saber cómo guardar los datos seleccionados en una variable para manipularlos como json.

Ya he logrado crear los valores a través de datos json.

_x000D_

_x000D_

function customMatcher(params, data) {_x000D_
			//show childs if search with parent_x000D_
		        data.parentText = data.parentText || "";_x000D_
		        if ($.trim(params.term) === '') {_x000D_
		            return data;_x000D_
		        }_x000D_
_x000D_
_x000D_
		        if (data.children && data.children.length > 0) {_x000D_
		            var match = $.extend(true, {}, data);_x000D_
_x000D_
		            for (var c = data.children.length - 1; c >= 0; c--) {_x000D_
		                var child = data.children[c];_x000D_
		                child.parentText += data.parentText + data.text;_x000D_
_x000D_
		                var matches = customMatcher(params, child);_x000D_
_x000D_
		                if (matches == null) {_x000D_
		                    match.children.splice(c, 1);_x000D_
		                }_x000D_
		            }_x000D_
_x000D_
		            if (match.children.length > 0) {_x000D_
		                return match;_x000D_
		            }_x000D_
_x000D_
		            return customMatcher(params, match);_x000D_
		        }_x000D_
_x000D_
		        var original = (data.parentText + ' ' + data.text).toUpperCase();_x000D_
		        var term = params.term.toUpperCase();_x000D_
_x000D_
		        if (original.indexOf(term) > -1) {_x000D_
		            return data;_x000D_
		        }_x000D_
_x000D_
		        return null;_x000D_
		    }_x000D_
	    _x000D_
		$("#multisearch").select2({_x000D_
		  language: "es",_x000D_
		  closeOnSelect: false,_x000D_
		  matcher: customMatcher,_x000D_
		  placeholder: "Comienza tu búsqueda",_x000D_
		  data: [{_x000D_
		      id: 0,_x000D_
		      text: 'Linea 1',_x000D_
		      children: [{_x000D_
		          id: 1,_x000D_
		          text: 'San Pablo'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 2,_x000D_
		          text: 'Pajaritos'_x000D_
_x000D_
		        },_x000D_
		        {_x000D_
		          id: 3,_x000D_
		          text: 'Las Rejas'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 4,_x000D_
		          text: 'Ecuador'_x000D_
		        }_x000D_
		      ]_x000D_
		    },_x000D_
		    {_x000D_
		      id: 5,_x000D_
		      text: 'Linea 2',_x000D_
		      children: [{_x000D_
		          id: 6,_x000D_
		          text: 'La Cisterna'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 7,_x000D_
		          text: 'El Parrón'_x000D_
_x000D_
		        },_x000D_
		        {_x000D_
		          id: 8,_x000D_
		          text: 'Lo Ovalle'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 9,_x000D_
		          text: 'Ciudad del niño'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 10,_x000D_
		          text: 'Pajaritos'_x000D_
		        }_x000D_
		      ]_x000D_
		    },_x000D_
_x000D_
		  ]_x000D_
		});_x000D_
	

_x000D_

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>_x000D_
	<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />_x000D_
	<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>_x000D_
<select multiple id="multisearch" style="width:500px">_x000D_
		</select>

_x000D_

_x000D_

_x000D_

Deseo poder capturar los valores seleccionados y almacenarlos en una variable con sus datos JSON

solución

Buenas tienes que tratar el select como a cualquier otro.

Para obtener los datos usa la function val() de Jquery

 $("#multisearch").val()

Espero te ayude saludos


Para obtener el valor del texto de cada item seleccionado usamos la función each() para iterar cada uno de los valores y agregarlos a un array en el que vamos a combinar el valor con el texto

Espero sea lo que buscas amigo

_x000D_

_x000D_

$("#obtenerDatos").click(function(){_x000D_
  //console.log($("#multisearch").val())_x000D_
  var arrayValor = $("#multisearch").val()_x000D_
  var arrayNombres = []_x000D_
  $(".select2-selection__rendered").find("li").each(function(index){_x000D_
    _x000D_
    if($(this).text()!=""){_x000D_
    var valorAnterior = arrayValor[index]_x000D_
    arrayValor[index] = {_x000D_
      id:valorAnterior,_x000D_
      valor:$(this).text().replace("×","")_x000D_
    }_x000D_
    }_x000D_
    _x000D_
  })_x000D_
  _x000D_
  console.log(arrayValor)_x000D_
})_x000D_
_x000D_
function customMatcher(params, data) {_x000D_
			//show childs if search with parent_x000D_
		        data.parentText = data.parentText || "";_x000D_
		        if ($.trim(params.term) === '') {_x000D_
		            return data;_x000D_
		        }_x000D_
_x000D_
_x000D_
		        if (data.children && data.children.length > 0) {_x000D_
		            var match = $.extend(true, {}, data);_x000D_
_x000D_
		            for (var c = data.children.length - 1; c >= 0; c--) {_x000D_
		                var child = data.children[c];_x000D_
		                child.parentText += data.parentText + data.text;_x000D_
_x000D_
		                var matches = customMatcher(params, child);_x000D_
_x000D_
		                if (matches == null) {_x000D_
		                    match.children.splice(c, 1);_x000D_
		                }_x000D_
		            }_x000D_
_x000D_
		            if (match.children.length > 0) {_x000D_
		                return match;_x000D_
		            }_x000D_
_x000D_
		            return customMatcher(params, match);_x000D_
		        }_x000D_
_x000D_
		        var original = (data.parentText + ' ' + data.text).toUpperCase();_x000D_
		        var term = params.term.toUpperCase();_x000D_
_x000D_
		        if (original.indexOf(term) > -1) {_x000D_
		            return data;_x000D_
		        }_x000D_
_x000D_
		        return null;_x000D_
		    }_x000D_
	    _x000D_
		$("#multisearch").select2({_x000D_
		  language: "es",_x000D_
		  closeOnSelect: false,_x000D_
		  matcher: customMatcher,_x000D_
		  placeholder: "Comienza tu búsqueda",_x000D_
		  data: [{_x000D_
		      id: 0,_x000D_
		      text: 'Linea 1',_x000D_
		      children: [{_x000D_
		          id: 1,_x000D_
		          text: 'San Pablo'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 2,_x000D_
		          text: 'Pajaritos'_x000D_
_x000D_
		        },_x000D_
		        {_x000D_
		          id: 3,_x000D_
		          text: 'Las Rejas'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 4,_x000D_
		          text: 'Ecuador'_x000D_
		        }_x000D_
		      ]_x000D_
		    },_x000D_
		    {_x000D_
		      id: 5,_x000D_
		      text: 'Linea 2',_x000D_
		      children: [{_x000D_
		          id: 6,_x000D_
		          text: 'La Cisterna'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 7,_x000D_
		          text: 'El Parrón'_x000D_
_x000D_
		        },_x000D_
		        {_x000D_
		          id: 8,_x000D_
		          text: 'Lo Ovalle'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 9,_x000D_
		          text: 'Ciudad del niño'_x000D_
		        },_x000D_
		        {_x000D_
		          id: 10,_x000D_
		          text: 'Pajaritos'_x000D_
		        }_x000D_
		      ]_x000D_
		    },_x000D_
_x000D_
		  ]_x000D_
		});

_x000D_

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>_x000D_
	<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />_x000D_
	<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>_x000D_
<select multiple id="multisearch" style="width:500px"  >_x000D_
		</select>_x000D_
    _x000D_
      <button id="obtenerDatos" type="button" name="button">Obtener datos del select</button>

_x000D_

_x000D_

_x000D_

Respondido por: Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *