Select dynamic as you type in a Textbox

Asked

Viewed 368 times

0

I have a scenario, which is this: I have a table, where there is a field called promotional code, where this promotional code can be typed and when it is typed it will have to do a SELECT in a option when the value is equal to the database will only appear in the option the necessary training. Only I need to make selects in real time, as it would be the best way to do this?

  • I understand you want to work with asynchronous calls. See if you have anything here that can help you https://stackoverflow.com/questions/14236296/asynchronous-function-call-in-php. you probably already have it fixed link here

2 answers

0

If the table where this select is made is well indexed. My suggestion is that 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 long as the user type in the input, you just type. Thus, you make only a single select and avoid overloading the database.

  • What if it’s 13,000 records, any hints? Why do I want to implement autocomplete in a 20-year-old database... = P

0

If this table doesn’t have too much record, I think Mario’s idea is a good one. You can play everything in a json and save it to html. If not, you can make an ajax while the guy type:

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
    });
});

Browser other questions tagged

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