What is the best way to transform the words in my JavaScript array into clickable links?

I am working on a search bar that autofills words and I want to turn those autofilled words into clickable links. For example, if I type "locations" in the search bar, I want it to autofill the word "locations" and turn it into a link that directs me to page2.html.

Currently, when I type "Locations" in the search bar, I get no results. If I type "<" I get the code displayed but it doesn't create a clickable link.

Below is the HTML and JavaScript code I am using. There is a specific code targeting the array at the bottom:

<form autocomplete="off" action="/action_page.php">
      <div class="SearchBar">
        <input id="myInput" type="text" name="Search2" placeholder="Search...">
      </div>
    </form>

    <script>

 var SW = ["<a href='Page2.html'>Locations</a>"];

    function SearchBar(inp, arr) {

 var currentFocus;
 inp.addEventListener("input", function(e) {
     var a, b, i, val = this.value;

     closeAllLists();
     if (!val) { return false;}
     currentFocus = -1;

     a = document.createElement("DIV");
     a.setAttribute("id", this.id + "SearchBar-list");
     a.setAttribute("class", "SearchBar-items");

     this.parentNode.appendChild(a);

     for (i = 0; i < arr.length; i++) {

       if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {

         b = document.createElement("DIV");

         b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
         b.innerHTML += arr[i].substr(val.length);

         b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";

             b.addEventListener("click", function(e) {

             inp.value = this.getElementsByTagName("input")[0].value;

             closeAllLists();
         });
         a.appendChild(b);
       }
     }
 });

 inp.addEventListener("keydown", function(e) {
     var x = document.getElementById(this.id + "SearchBar-list");
     if (x) x = x.getElementsByTagName("div");
     if (e.keyCode == 40) {

       currentFocus++;

       addActive(x);
     } else if (e.keyCode == 38) {

       currentFocus--;

       addActive(x);
     } else if (e.keyCode == 13) {

       e.preventDefault();
       if (currentFocus > -1) {

         if (x) x[currentFocus].click();
       }
     }
 });
 function addActive(x) {

   if (!x) return false;

   removeActive(x);
   if (currentFocus >= x.length) currentFocus = 0;
   if (currentFocus < 0) currentFocus = (x.length - 1);

   x[currentFocus].classList.add("SearchBar-active");
 }
 function removeActive(x) {

   for (var i = 0; i < x.length; i++) {
     x[i].classList.remove("SearchBar-active");
   }
 }
 function closeAllLists(elmnt) {

   var x = document.getElementsByClassName("SearchBar-items");
   for (var i = 0; i < x.length; i++) {
     if (elmnt != x[i] && elmnt != inp) {
     x[i].parentNode.removeChild(x[i]);
   }
 }
 }

 document.addEventListener("click", function (e) {
   closeAllLists(e.target);
 });
 }
    </script>

    <script>
 SearchBar(document.getElementById("myInput"), SW);
 </script>

Answer №1

To generate the suggestion items, utilize the document.createElement method.
Here's how:

var SW = ["Locations", "test"];
var links = ["https://shadowlp174.4lima.de","https://stackoverflow.com"];

function SearchBar(inp, arr, links) {
  var currentFocus;
  inp.addEventListener("input", function(e) {
    var div, b, i, val = this.value;

    closeAllLists();
    if (!val) {
      return false;
    }
    currentFocus = -1;

    div = document.createElement("div");
    div.id = this.id + "SearchBar-list";
    div.classList.add("SearchBar-items");
    this.parentNode.appendChild(div);

    for (i = 0; i < arr.length; i++) {
      if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
        var a = document.createElement("a");
        a.href = links[i];
        a.setAttribute("suggestion", arr[i]);
        div.appendChild(a);

        let strong = document.createElement("strong");
        strong.innerHTML = arr[i].substr(0, val.length);
        let span = document.createElement("span");
        span.innerHTML = arr[i].substr(val.length, arr[i].length - 1);
        a.appendChild(strong);
        a.appendChild(span);

        a.addEventListener("click", function(e) {
          inp.value = this.getAttribute("suggestion");
          closeAllLists();
        });
      }
    }
  });

  inp.addEventListener("keydown", function(e) {
    var x = document.getElementById(this.id + "SearchBar-list");
    if (x) x = x.getElementsByTagName("div");
    if (e.keyCode == 40) {

      currentFocus++;

      addActive(x);
    } else if (e.keyCode == 38) {

      currentFocus--;

      addActive(x);
    } else if (e.keyCode == 13) {

      e.preventDefault();
      if (currentFocus > -1) {

        if (x) x[currentFocus].click();
      }
    }
  });

  function addActive(x) {

    if (!x) return false;

    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);

    x[currentFocus].classList.add("SearchBar-active");
  }

  function removeActive(x) {

    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("SearchBar-active");
    }
  }

  function closeAllLists(elmnt) {

    var x = document.getElementsByClassName("SearchBar-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }

  document.addEventListener("click", function(e) {
    closeAllLists(e.target);
  });
}
SearchBar(document.getElementById("myInput"), SW, links);
<form autocomplete="off" action="/action_page.php">
  <div class="SearchBar">
    <input id="myInput" type="text" name="Search2" placeholder="Search...">
  </div>
</form>

You can specify the destinations in the array. I have set it to two demonstration sites that are accessible to everyone.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to interact with the reappeared element selected using jQuery

After using developer tools in both Chrome and Firefox, I successfully created an XPath for a specific element. However, when attempting to click on the element by hovering over the returned value $x(xpath), I encountered an error. The error message read: ...

The clingy navigation bar hinders smooth scrolling to the content

My website has an image where users can click on elements to scroll down to text. However, I'm facing a problem because there is a sticky menu at the top of my website. How can I ensure that the scrolling works correctly with the sticky menu included? ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Mismatched communication in the menu between the list item <li> and the anchor tag <a>

Why is the dropdown ul in 'Menu Item 2' not aligned at the top of its parent li element? Despite setting the dropdown ul CSS as: position:absolute; top:0; left:0; I expected it to cover the entire parent element from the top left corner. Some ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

Engaging with Electron through an HTML file

Forgive my lack of experience, but I'm diving into the world of Electron and feeling a bit overwhelmed. Here's a snapshot of what I've got so far in my project: package.json: ... "main": "main.js", "scripts": { "start": "electron ." } . ...

Eavesdrop on outbound requests on a web page using JavaScript

As I develop a single-page application that integrates a third-party analytics tool (such as Heap, Segment, Mixpanel, etc.), I am looking to actively monitor the outgoing HTTPS requests from my app and take necessary actions, such as logging. I am curious ...

Error message: "wp is not defined" appears when using TinyMCE, Bootstrap Modal, and URL Parameter together

Currently utilizing Bootstrap 5 alongside WordPress 6.2 In the process of developing a WordPress plugin, where I have successfully created a Dashboard and an All Content page. On the Dashboard page, users can find a list of the most recently created cont ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

Tips on removing pesky favicons

Not too long ago, I purchased a domain and configured it with Wordpress. Eventually, I decided to switch to a static landing page so I uninstalled Wordpress. But now there's an unfamiliar favicon that has appeared on my site. Even after deleting all ...

Concealing <div> elements in Laravel 7

I'm working on my home page in the blade.php file and I have multiple divs. If the value of {{$user[0]->d1}} is equal to 1, I need to hide the div. However, I'm struggling to figure out how to do this. {{$user[0]->d1}} //I need to disable ...

Is it possible to include padding within a textarea element?

Is it possible to add some left margin inside a textarea? I would like there to be some extra space because I am using an image icon as my button within the textarea, and when I type, the words end up covering the image. <div id="inputBox"> < ...

With the use of discreet JavaScript, the parameter is not empty; instead, it contains values

Previously, my JavaScript code was functioning correctly when it was within the same page as my cshtml file: function SaveEntity() { // more code here alert(entity.FirstName); /* this shows that entity's properties have values */ $.post( ...

Is it simple to customize the color of the close button in Bootstrap 5?

Bootstrap's v5 release brings updated styling to various components, including the close button. In previous versions, the close button had an "x" that could be easily styled with text properties, like inheriting color from its parent. However, in v5, ...

Expanding scrollbar when hovered over

My goal for a landing page design is to showcase a centered logo at the top, followed by three images with borders arranged side by side, each with a bit of padding. When a user hovers over any of these images, I want the text on that image to slide to the ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

The function appears to be failing to execute

I'm currently working on a dynamic search bar using AJAX to retrieve results from a database. I've noticed that when I check in the debugger, the code isn't triggering the handleSuggest() function which is responsible for updating the inner ...

Which method is more appropriate for my request - GET or POST? Or should I consider

Recently, I've been exploring the world of get and post methods and could use some guidance! Within my App.js file, there is a user text input field and a submit button. I have a couple of tasks in mind for handling this information: Retrieve a str ...

Issues with JQuery Radio button selection in Internet Explorer 6

Here is some code that I am working with: <input type="radio" name="HotelSearch_Measure" value="Miles"> <input type="radio" name="HotelSearch_Measure" value="KM"> While this code functions properly in IE9, Chrome, and Firefox, it does not wor ...