Skip to content
Advertisement

jQuery UI Autocomplete

I am using jQuery UI’s autocomplete plugin and everything is well and good except for that fact that when a user clicks the value they want the function I have assigned to the “select:” method fires before the value of the field is changed. So if I type “Foo” in the input field, then click the autocomplete match for “Foo Bar” the function detects the value as what was typed (in this case “Foo”) as opposed to the value which was selected from the autocomplete list. Once the function fires (in this case I just have an alert box popup with this.value) the value of the input field is set to the value selected via the autocomplete list. This problem does not occur if the user selects the option with the keyboard (arrow keys->tab), only when the mouse is used.

  $(function()
  {
    var aEmps = 
    [
<?php
echo $sEmps;
?>    
    ];

    $("#slast").bind( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
          $( this ).data( "autocomplete" ).menu.active ) 
          { event.preventDefault(); }
    })
    .autocomplete({
      source: aEmps,
      select: function(event, ui)
      {
        var aName = $(this).val();
        alert(aName);
      }
    })
  });

Since most users will be interacting with this using their mouse I have to find a way to get the value set before firing the “select:” function. I believe I can accomodate for this by adding a condition to the statement prior to the auto complete but I need some help finding the right syntax.

Advertisement

Answer

After trying a number of approaches I found that by simply binding the callback function to the close event works very well. I added some error handling to catch values that aren’t selected from the list and I am off and running!

Here is the updated code:

  $(function()
  {
    var aEmps = 
    [
<?php
echo $sEmps;
?>    
    ];

    $("#slast").bind( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
          $( this ).data( "autocomplete" ).menu.active ) 
          { event.preventDefault();}
    })
    .autocomplete({
      source: aEmps,
      close: function(event, ui)
      {
        alert(this.value);
      }      
    })
  });
Advertisement