Catch event click on jQuery autocomplete value

Asked

Viewed 1,304 times

1

I’m developing a function in Jquery that uses the component Autocomplete where I search the company name and change the company name in another field.

Example:

Field1 (autocomplete) passes information to Field2 when it is clicked on the option shown in the Autocomplete.

My problem is: Knowing what value was clicked and the click event to pass the information to the other field.

Follows code snippet:

var empresas = ['teste','teste2'];
$( "#e" ).autocomplete({
    minLength: 2,
    autoFocus: true,
    source: empresas
});
  • 2

    select: function (e, i) {
 console.log(i.item.val); }, have tried?

  • I had not tried because I did not know what the function was to catch the event, and had not found a solution, it worked this exchanging val for value

  • Glad I could help, if clicking run down there will see working.

2 answers

1


You can use the event select. I made a test based on the example of the site itself Jquery-UI.

Would look like this:

$( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags,
      select: function (e, i) {
        document.getElementById("msg").innerHTML = "Você selecionou o item: " + i.item.value
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css">

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
  <div id='msg'>
   </div>
</div>

0

Simply overwrite the original callback function:

function AutoCompleteSelectHandler(event, ui)
{                        
    $('#Campo2').val(ui.item.value);
}

or in this way by adding the callback select: API jQuery

var empresas = ['teste','teste2'];
$( "#e" ).autocomplete({
    minLength: 2,
    autoFocus: true,
    source: empresas,
    select: function( event, ui ) { $('#Campo2').val(ui.item.value); }
});
  • It worked out, the difference between search by select and label by value

Browser other questions tagged

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