jQuery Autocomplete > Select > Link
Asked Answered
S

1

7

I have this code implemented and I like how straight forward it is because I plan to add ALOT to the Source -- however for the life of me I cannot figure out how to add the selected one as a Link.

EG > Begin Typing > Autofill works > Select > Go to that URL

Current Code:

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("input#autocomplete").autocomplete({
    source: ["NYC", "LA", "Philly", "Chitown", "DC", "SF", "Peru"]
});
  });
  </script>
</head>
<body style="font-size:62.5%;">

<input id="autocomplete" />

</body>
</html>

I found a few discussions about this on here, but none of the code suggestions had worked. How do I add a URL associated with the values above; I'd love if I could keep the same syntax and near the values just add; EG: "peru" www.peru.com

Shawndashawnee answered 25/6, 2012 at 23:24 Comment(0)
B
18

You could add a url property to each object in the source array and then set window.location to that URL when the user selects an item:

$(document).ready(function() {
    $("input#autocomplete").autocomplete({
        source: [
             { value: "NYC", url: 'http://www.nyc.com' }, 
             { value: "LA", url: 'http://www.la.com' },
             { value: "Philly", url: 'http://www.philly.com' },
             { value: "Chitown", url: 'http://www.chitown.com' },
             { value: "DC", url: 'http://www.washingtondc.com' },
             { value: "SF", url: 'http://www.sanfran.com' },
             { value: "Peru", url: 'http://www.peru.com' }
        ],
        select: function (event, ui) {
            window.location = ui.item.url;
        }
    });
});
Blythebm answered 25/6, 2012 at 23:28 Comment(7)
AH. Sorry, they will not be exact Name > .com; Some will be "NYC" > www.samplenotnyc.com -- I was just hoping to have the URL near the value within the code for updating.Shawndashawnee
So can you change the source array? I'm not sure what you mean by "Near the value"Blythebm
Actually I think I see what you mean. Please see the updated answer.Blythebm
YES! This looks great -- let me give it a whirl, thanks dude!Shawndashawnee
Would there be any limit / issue adding a few hundred values with this code?Shawndashawnee
Mmm, I don't think a few hundred would matter, but when you get into the thousands you would definitely want to consider using a server-side source.Blythebm
super , can i also add source.php in place of the json values ?Lucretialucretius

© 2022 - 2024 — McMap. All rights reserved.