Fill select with JQuery

0

I'm using the JQuery autocomplete and it's working normally. But it is populating a type text that contains only one field (the txt itself) to fill in.

I would like a select to be filled in instead of txt.

Someone help me?

Follow the code

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery UI Autocomplete - Default functionality</title>
    <link rel="stylesheet" href="http:////code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" href="style.css">


    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script><scriptsrc="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
    $(function() {
        var clientes = [
            "Fulano",
            "Bertanbo"
        ];
        $( "#clientes" ).autocomplete({
            source: clientes
        });
    });
    </script>
</head>
<body>

<div class="ui-widget">
    <label for="clientes">clientes: </label>
    <input id="clientes">
</div>


</body>
</html>

I would like to change the

<input id="clientes">

By

<select name="clienteEscolhido">
  <option value=""></option>
</select>
    
asked by anonymous 19.09.2015 / 15:04

1 answer

3

A solution is found using <input type="text" /> and <input type="hidden" /> . It consists of picking the event of your auto complete selection and setting the description in the text and the Id to be sent to your backend field in the hidden field:

HTML:

<input type="text" id="descricao" />
<input type="hidden" name="idQueVaiParaSeuBackEnd" id="id" />

JavaScript:

var source = [{
    label: "Tom Smith",
    value: "1234"
}, {
    label: "Tommy Smith",
    value: "12321"
}];

$("#descricao").autocomplete({
    source: source,

    //quantidade de caracteres para começar a buscar
    minLength: 3,

    //evento de quando você seleciona uma opção   
    select: function (event, ui) {         

        //seto a descrição para aparecer para usuario no input text
        $("#descricao").val(ui.item.label);

        //seto o id para ir para seu backend :D
        $("#id").val(ui.item.value); 

        event.preventDefault();
    }
});

CSS:

<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/themes/black-tie/jquery-ui.css">

JS:

<script src="http://code.jquery.com/jquery-1.6.2.js"></script><scriptsrc="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/jquery-ui.min.js"></script>

Follow the jsfiddle .

    
19.09.2015 / 16:28