Select dynamic as you want by typing in a TextBox

0

I have a scenario where it is the following: I have a table where there is a field called a promotional code where this promo code can be typed and when it is typed it will have to make a SELECT in a option when the value is equal to the database just goes appear in%% of the required training. But I need to do selects in real time, what would be the best way to do that?

    
asked by anonymous 20.03.2017 / 13:56

2 answers

0

If the table where the select is made is well indexed. My suggestion is you make a full select on it even before the user input in the field. You store the result array somewhere that you can manipulate via javascript, and as you type in the input, you just filter. So you only do a single select and avoid overloading the database.

    
20.03.2017 / 14:00
0

If this table does not have too many records, I think Mario's idea is good. You can play everything in a json and write to html. If not, you can do an ajax while the guy types:

var $input = $('.search');
$input.on('keyup', function(e) {
    // O que vai buscar
    var needle = $.trim($suggestInput.val());

    // Precisa ter ao menos 3 caracteres
    if(needle.length < 3) {
        if(needle.length > 0 || code == 27)
            $suggestContainer.fadeOut('fast');

        return false;
    }

    // Se foi o último buscado não busca de novo
    if(needle == $input.attr('data-last')) {
        // Aqui você mostra os resultados
        return false;
    }

    // Mostra o loading...

    // Se já tem alguma requisição em andamento, cancela ela
    if(ajaxRequest && ajaxRequest.readyState != 4){
        ajaxRequest.abort();
    }
    // Faz a busca
    ajaxRequest = $.ajax({
        url: '/search-trainings',
        type: 'GET',
        dataType: 'json',
        data: {q: needle},
    }).done(function(result) {
        $input.attr('data-last', needle);
        // Faz aqui o que você precisa
    }).fail(function() {
        // Se der erro na requisição
    }).always(function() {
        // Retira o loading
    });
});
    
20.03.2017 / 14:59