Dynamic Combobox with Codeigniter 3

Asked

Viewed 982 times

0

The basic idea is similar to combobox of states and cities, that when selecting a state, the next select returns the corresponding cities.

In my case I cannot list these fields in the second select (which would equal cities).

With the following codes, the only event is that when selecting any of the fields, the second select receives an option with the 'choice' name, according to the JS reset script.

I did a test with the method Listfiltropersonalized and the same is returning the data correctly, the problem lies in the asynchronous transition.

Note: The code is based on this article.

Obs²: I know that in the option I put the value 'test'..

Follow snippets of code:

Essays (Controller)

defined('BASEPATH') OR exit('No direct script access allowed');

class Redacoes extends CI_Controller {

function __construct() {
    parent::__construct();
}

public function index() {
    //Carregar o model
    $this->load->model('Read_model');

    $data['redacoes'] = $this->Read_model->ListaRedacoes('Matricula', 'asc');

    if ($this->input->post('frmFiltro')):
        $data['filtros'] = $this->Read_model->listaFiltroPersonalizado($this->input->post('frmFiltro'));
    endif;

    $this->template->load('base', 'home', $data);
}
}

Read (Model)

class Read_model extends CI_Model {

private $table = 'redacoes';

public function __construct() {
    parent::__construct();
}

function ListaRedacoes($sort = 'Data', $order = 'desc', $limit = null, $offset = null) {

    $this->db->order_by($sort, $order);

    if ($limit):
        $this->db->limit($limit, $offset);
    endif;

    $query = $this->db->get($this->table);
    return $query->result();
}

public function ListaFiltroPersonalizado($filtro) {
    $this->db->select($filtro);
    $this->db->join('aluno_2016', 'aluno_2016.matricula_aluno = redacoes.Matricula');
    $this->db->group_by($filtro);
    $this->db->order_by($filtro, 'asc');
    $query = $this->db->get($this->table);
    return $query->result();
}

public function FiltraRedacoes($campo, $filtro) {
    $this->db->join('aluno_2016', 'aluno_2016.matricula_aluno = redacoes.Matricula');
    $this->db->where($campo, $filtro);
    $query = $this->db->get($this->table);
}
}

home (view)

<form method="post">
    <div class="form-group">
        <div class="input-group">
            <label class="input-group-addon"><i class="fa fa-search"></i></label>
            <select name="frmFiltro"  id="frmFiltroPersonalizado" class="form-control" required="required">
                <!--onchange="this.form.submit()"-->
                <option value="" selected>-- Selecione um filtro --</option> 
                <option value="Tipo">Tipo</option> 
                <option value="unidade_aluno">Unidade</option>
                <option value="periodo_aluno">Período</option>  
                <option value="nome_curso">Curso</option>  
                <option value="turma_aluno">Turma</option>  
                <option value="sala_aluno">Sala</option>  
                <option value="descricao_curso">Descricao curso</option>  
            </select>
        </div>
    </div>
    <div class="form-group">
        <div class="input-group">
            <label class="input-group-addon"><i class="fa fa-search"></i></label>
            <select name="frmFiltroValor" id="frmFiltroPersonalizadoValor" class="form-control" requireds="required">
                <option value="" selected>-- Selecione --</option> 

                <?php foreach ($filtros as $filtro): ?>
                    <option value="">teste</option>
                <?php endforeach; ?>

            </select>
        </div>                                        
    </div>

    <div class="form-group">
        <input class="btn btn-primary" type="submit">
    </div>
</form>

Javascript (Ajax)

var path = '<?= base_url(); ?>'
            $(function () {

                $("select[name=frmFiltro]").change(function () {

                    filtro = $(this).val();

                    if (filtro === '')
                        return false;

                    resetaCombo('frmFiltroValor');

                    $.getJSON(path + 'redacoes/filtro/' + filtro, function (data) {

                        var option = new Array();

                        $.each(data, function (i, obj) {

                            option[i] = document.createElement('option');
                            $(option[i]).attr({value: obj.id});
                            $(option[i]).append(obj.nome);

                                $("select[name='frmFiltroValor']").append(option[i]);

                            });

                        });

                    });

                });

                function resetaCombo(el) {
                    $("select[name='" + el + "']").empty();
                    var option = document.createElement('option');
                    $(option).attr({value: ''});
                    $(option).append('Escolha');
                    $("select[name='" + el + "']").append(option);
                }

.htacess

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
  • What’s the matter, options are not created?

  • Exactly. I tried several ways and no longer know if it is due to my controller that does not send the information, or if it is ajax that does not receive.. I went to the console and the request is done normally, but an option is always created with the 'choice' value'.

  • 1

    have tried? $.each(data, function (i, item) {&#xA; $('select[name='frmFiltroValor']').append($('<option>', { &#xA; value: item.id,&#xA; text : item.nome &#xA; }));&#xA;});

  • Hello, good morning! I believe the reported syntax is incorrect.. I tried several ways to replace here and all present error, so much so that I locked all my js. I replace the code with this: $. each(data, Function (i, obj) { option[i] = Document.createelement('option'); $(option[i]). attr({value: obj.id}); $(option[i]). append(obj.name); $("select[name='frmFiltroValor']"). append(option[i]); });

  • @Thiagobarros, have you tried the syntax I suggested? Try explaining better what you say as "failed". Is the error in the dropdown assembly? Is the error in JSON? Error in JS? What exactly is the error? Put the debug information you have :)

  • With my current code no error is shown. However, in the second select an option is created with the text 'Choice'. I tried with its syntax and besides not having worked, stopped my other functions. Most likely I am overwriting the code incorrectly (I believe it to be), or the syntax you gave me is incorrect.

  • So your JSON return is not working... already tested? 'Choice' is appearing because you call the method resetaCombo('frmFiltroValor');. Can you tell me the value of the variable var path = '<?= base_url(); ?>'?

  • Can we open a chat? Because we will most likely pollute code comments. And after solving, one of us puts the answer here with the correct script. It can be?

Show 4 more comments

1 answer

1


You need to have a solid JSON object to be able to display in select dynamically. A solid JSON example for an X query:

[{"resultadoBusca": "teste"},{"resultadoBusca": "teste2"},{"resultadoBusca": "teste3"}]

Having the solid json, just go through the array in JS and consolidate the information within your select:

$.each(data, function (i, item) { $('#frmFiltroValor').append($('<option>', { value: i, text : item.resultadoBusca })); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.