Reginald1234
Reginald1234

Reputation: 335

Jquery autocomplete widget "select( event, ui )"

I use jquery for my autocomplete searchbar

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/black-tie/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

When typing a search result in the search bar, a list of results pop-up (auto-completes) and it automatically focuses on the first results. (This is what I want)

When clicking with my mouse (left button) on the first results it direct me to the correct page (href look at my JS code). (This is what I want)

When I press Enter the first (focused) search result becomes visible in the search bar itself, instead of redirecting me to the correct page.

How can I fix this issue, I'thinking about the "select( event, ui )".

My javascript

 $(function() {   
      var projects = [{
        label: "Bitcoin (BTC)",
        icon: "./alt/alt_logo/bitcoin.png",
        href: "./alt/alt_info/bitcoin.html"
      }, {
        label: "Ethereum (ETH)",
        icon: "./alt/alt_logo/ethereum.png",
        href: "./alt/alt_logo/ethereum.html"
      }, {
        label: "Litecoin (LTC)",
        icon: "./alt/alt_logo/litecoin.png",
        href: "./alt/alt_logo/litecoin.html"
      }, {
        label: "Cardano (ADA)",
        icon: "./alt/alt_logo/cardano.png",
        href: "./alt/alt_logo/cardano.html"
      }];

              $(".field_values").autocomplete({

/*testing*/
  select: function(ul, item) {
    if (e.which == 13)  {
        alert ("hello world!");
        }
  },
/*testing*/
                autoFocus: true,
                source: projects,
                create: function() {
                  $(this).data('ui-autocomplete')._renderItem = function(ul, item) {
                    return $('<li>')
                      .append('<a href="' + item.href + '"><img class="icon" src="' + item.icon + '" />'  + item.label + '</span>' + '<br>'  + '</a>')
                      .appendTo(ul);
                  };
                }  
              });  
    });

Thanks for reading and helping, If you need more information just tell me.

Upvotes: 0

Views: 515

Answers (1)

NayoR
NayoR

Reputation: 721

Reffering to jQuery API documentation, you may use select attribute ;

$(".field_values").autocomplete({
    autoFocus: true,
    source: projects,
    create: function() {
        $(this).data('ui-autocomplete')._renderItem = function(ul, item) {
            return $('<li>')
              .append('<a href="' + item.href + '"><img class="icon" src="' + item.icon + '" />'  + item.label + '</span>' + '<br>'  + '</a>')
              .appendTo(ul);
        };
    },
    select: function(event, ui) {
        $(this).first().click();
    }
});

Upvotes: 1

Related Questions