简体   繁体   中英

How to modify this JQuery function

I'm using jquery.autocomplete to display search suggestions. Right now the function takes the value and insert it behind "/collections/".

I like to give each tag a custom url. If anyone could show me how to do implement this would be awesome.

 $(function(){ var tags = [ { value: 'product1' }, { value: 'product2' }, { value: 'product3' }, { value: 'product4' } ]; $('#autocomplete1').autocomplete({ lookup: tags, lookupFilter: function (suggestion, originalQuery, queryLowerCase) { return suggestion.value.toLowerCase().indexOf(queryLowerCase) === 0; }, onSelect: function (suggestion) { document.location.href = "/collections/" + $(this).val() } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.24/jquery.autocomplete.js"></script> <form method="get" id="searchbar" action="/search"> <button type="submit" value="Search"> <span class="icon-search"></span> </button> <input type="text" name="q" autocomplete="off" id="autocomplete1" placeholder="Search"/> </form>

So something like this:

$(function(){
  var tags = [      
    { value: 'product1', url: '/collections/product1' },
    { value: 'product2', url: '/collections/product2b' },
    { value: 'product3', url: '/collections/product3a' },
    { value: 'product4', url: '/collections/product4b' }, 
  ];

For this you can use the ui.item.{parameter} , so in your case, ui.item.url

in this instance when you click on a value from the autocomplete the ui.item is set to:

[object Object] {
  label: "product1",
  url: "/collections/product1",
  value: "product1"
}

which you can then easily select the url and point the document location

 $(function() { var availableTags = [ { url: '/collections/product1', value: 'product1' }, { url: '/collections/product2b', value: 'product2' }, { url: '/collections/product3a', value: 'product3' }, { url: '/collections/product4b', value: 'product4' } ]; $( "#autocomplete1" ).autocomplete({ source: availableTags, select: function (event, ui) { document.location.href = ui.item.url; } }); });
 <!DOCTYPE html> <html> <head> <link href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="https://code.jquery.com/jquery-1.11.3.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="ui-widget"> <label for="tags">Tags: </label> <input type="text" name="q" autocomplete="off" id="autocomplete1" placeholder="Search"/> </div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM