Assigning value using val (value) or attr ('value', value) does not work

0

I'm using typeahead , which works as follows, every text I type in the field takes the value of the field, goes to a database, searches and creates a dropdown with the values found.

It works perfectly, but I wanted to as soon as the enter button was pressed the field would populate with the first dropdown value.

I can get the first value with:

var valor = $(".tt-suggestion p").first().text();

But when trying to set it on the field using:

$("#cidade_estado").val(valor);

or

$("#cidade_estado").val(valor);

Nothing happens.

I know that he is entering into the if as he does the:

$("#telefone").focus();

Usually shows the values in the console.

$(document).ready(function () {
    $('input.cidade_estado').typeahead({
        name: 'municipio',
        remote: 'action/getMunicipios.php?query=%QUERY'
    }).keypress(function (e) {
         var valor = $(".tt-suggestion p").first().text();
         console.log("Aqui: " + valor);
        if (e.which == 13) {
            console.log("13: " + valor);
            $("#cidade_estado").val(valor);
            $('#cidade_estado').attr('value', valor);
            $("#telefone").focus();
            return false;
        }
    });
});

html:

            <form id="formemail" action="action/enviaemail.php" method="post">
                <input name="nome" type="text" placeholder="Nome completo">
                <input name="empresa" type="text" placeholder="Empresa">
                <input id="cidade_estado" name="cidade_estado" class="cidade_estado" type="text" placeholder="Cidade">
                <input name="telefone" class="grupocontato" id="telefone" type="text" placeholder="Telefone">
                <input name="email" class="grupocontato" type="text" placeholder="Email">
                <textarea name="mensagem" placeholder="Mensagem"></textarea>
                <input class="btnContato" type="submit" value="Enviar">
            </form>

Console:

    
asked by anonymous 18.09.2017 / 17:12

1 answer

0

With the help of AnthraxisBR the issue has been resolved:

$(document).ready(function () {
    $(".twitter-typeahead span").text('dfsd');
    var campo = $('input.cidade_estado');
    campo.keypress(function (e) {
         var valor = $(".tt-suggestion p").first().text();
        if (e.which == 13) {
            $(".tt-suggestion p").trigger( "click" );
            $("#telefone").focus();
            return false;
        }
    }).typeahead({
        name: 'municipio',
        remote: 'action/getMunicipios.php?query=%QUERY'
    });
});
    
18.09.2017 / 18:37