I can not select an option in select2


#1

Code:

function recolher(n1){
campos.idAluno = document.getElementById(“coluna_”+n1+“0").innerHTML;
campos.nome = document.getElementById("coluna
”+n1+“1").innerHTML;
campos.matricula = document.getElementById("coluna
”+n1+“2").innerHTML;
campos.idCurso = document.getElementById("coluna
”+n1+“3").value;
campos.anoEntrada = document.getElementById("coluna
”+n1+“4").innerHTML;
campos.anoTermino = document.getElementById("coluna
”+n1+“5").innerHTML;
campos.obs = document.getElementById("coluna
”+n1+"_6").innerHTML;
document.getElementById(“id_aluno”).value = campos.idAluno;
document.getElementById(“nome”).value = campos.nome;
document.getElementById(“matricula”).value = campos.matricula;
$(’#selcurso’).val(campos.idCurso);
$(’#selcurso’).trigger(‘change’);
document.getElementById(“anoEntrada”).value = campos.anoEntrada;
document.getElementById(“anoTermino”).value = campos.anoTermino;
document.getElementById(“obs”).value = campos.obs;
}
$(document).ready(function() {
selectViaAjax("#selcurso", “curso”, “nome”, “id_curso”);
});


#2

Can you provide the code that shows how you are initializing your Select2? I’m guessing that’s the selectViaAjax function.

Also, can you provide an example of the values in campos.idCurso? I notice you are using the .value property for campos.idCurso, but you’re using .innerHTML for all the other values. I’m guessing that the "coluna"+n1+"x" values refer to cells in a table, so I don’t think .value will return anything.

If you are loading data into your Select2 using AJAX, then the .val method you’re using to programmatically select an item in your Select2 probably will not work, because the Select2 only loads content into the HTML <select> element after the user performs a search and selects an item in the Select2. This is described in more detail in the Select2 documentation, here.


#3

Code initializing my Select2:

function tabelaViaAjax(tabela, page, porPagina){
$.ajax(listar/${tabela}.php, {
method: ‘POST’,
dataType: ‘json’,
data: {
page: page,
porPagina: porPagina
}
}).done(function(json) {
var i = 0;
var plural = tabela + (tabela.endsWith(‘s’)? ‘es’ : ‘s’);
$(’#tabela’).attr(“page”, page);
$(#${tabela}s).html("");
$("#divbtns").html("");
for(var registro in json.resultado){
var j = 0;
registro = json.resultado[registro];
$(#${plural}).append(<tr id='linha_${i}' onclick='recolher(${i})'>);
for(var key in registro){
var valor = registro[key];
$(#linha_${i}).append(<td id='coluna_${i}_${j++}'>${valor}</td>);
}
$(#linha_${i++}).append(’’);
}
if(page != 0)
$("#divbtns").append(<button class='btn btn-default' onclick='comunicar(${page - 1})'> Voltar </button>);
if(page+1 < json.total)
$("#divbtns").append(<button class='btn btn-default' onclick='comunicar(${page + 1})'> Avançar </button>);
});
}

The problem is not the value of campos.idCurso, because I test it and the value is corect. Do you want all of the code to you analize that ?

thaks


#4

I don’t see any code that initializes a Select2 widget in the code you pasted above. This code appears to fill in an HTML <table> with data that was retrieved via AJAX. I need to see the code that initializes #selcurso.


#5

I retrieve the campos.idCurso from a function recolher where it sends the value of the selected row in the table. In this first code, where is it getting this value from the table, and selecting that value in select2:

function recolher(n1){
campos.idAluno = document.getElementById(“coluna”+n1+“0").innerHTML;
campos.nome = document.getElementById("coluna”+n1+“1").innerHTML;
campos.matricula = document.getElementById("coluna”+n1+“2").innerHTML;
campos.idCurso = document.getElementById("coluna”+n1+“3").value;
campos.anoEntrada = document.getElementById("coluna”+n1+“4").innerHTML;
campos.anoTermino = document.getElementById("coluna”+n1+“5").innerHTML;
campos.obs = document.getElementById("coluna”+n1+"6").innerHTML;
document.getElementById(“id_aluno”).value = campos.idAluno;
document.getElementById(“nome”).value = campos.nome;
document.getElementById(“matricula”).value = campos.matricula;
$(’#selcurso’).val(campos.idCurso);
$(’#selcurso’).trigger(‘change’);
document.getElementById(“anoEntrada”).value = campos.anoEntrada;
document.getElementById(“anoTermino”).value = campos.anoTermino;
document.getElementById(“obs”).value = campos.obs;
}

Already in this second code, it shows where eh is called the ajax function where it calls the function selectViaAjax:

<select class='js-example-basic-multiple form-control' id='selcurso' name='selCurso' size ='1'></select>

$(document).ready(function() {
selectViaAjax("#selcurso", "curso", "nome", "id_curso");
});

And finally this is the function selectViaAjax:

function selectViaAjax(identificador, tabela, principal, value) {
$(identificador).select2({
ajax: {
url: 'php_action/asJSONSelect2.php',
type: "POST",
dataType: 'json',
data:  function (params) {
return {
q: params.term
}
},
data: jQuery.param({tabela: tabela,valor:principal,codigo:value}),
processResults: function (data, params) {
var search = params.term? params.term : "";
data.results = data.results.filter(function(value){
return value.text.includes(search);
});
return data;
}
}
});
}

Where it passes through this file called asJSONselect2.php that contains this code:

<?php
require "../_classe/metodos.php";
include("conexao.php");
$metodos = new Metodos;
$metodos->gerarJSONSelect2($conn, $_POST["tabela"], $_POST["valor"], $_POST["codigo"]);
?>

And it arrives to this last function filling the select2 with the information of the database:

function gerarJSONSelect2($conn, $tabela,$campoLiteral,$campoCodigo){
$db = new mysqli('localhost', 'root', '', 'estagio');
$sql = "SELECT * FROM ".$tabela;
$query = mysqli_query($conn, $sql);
$registros = array();
while ($registro=mysqli_fetch_array($query)){
$registros[] = array("text" => $registro[$campoLiteral], "id"=>$registro[$campoCodigo]);
}
$resultados = array("results" => $registros);
echo json_encode($resultados);
}

The only problem I am having to terminate the program, is not being able to do the function recolher select the value I get from the table in select2, because the code I used is not working, I already checked to see if it was the value of campos.idCurso, but this is getting the right amount. If you can give me the right code for this case. I thank you for your help.


#6

Does the selectViaAjax function get called before the recolher function is called? The recolher function assumes the Select2 widget has already been initialized.Also, dince you are using an AJAX data source for the Select2, it must be initialized and the user must have entered a query; otherwise, no data will be present in the Select2 when the recolher function tries to select a value.

Note that, when using an AJAX data source with the Select2, the data source is not queried until the user types a search term.

If the recolher function is called before the Select2 has any data, then what you probably want to do is “pre-select” the value the user chose from the table. To do that with an AJAX-based Select2, you basically have to insert the item you want to pre-select into the underlying HTML <select>. The instructions are here: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2