Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar:

<div class="md-form mt-0">
   <input class="form-control" id="myInput" type="text" placeholder="Search" aria-label="Search">
</div>

In addition, I have these four anchor tags:

<a class="article-link" href="https://www.anafiotika.gr/el/">Anafiotika Cafe-Restaurant</a>
<a class="article-link" href="https://www.anafiotika.gr/el/">Joli Cafe</a>
<a class="article-link" href="https://www.anafiotika.gr/el/">Five Guys Burger House</a>
<a class="article-link" href="https://www.anafiotika.gr/el/">ATH Cafe Bar</a>

My goal is to dynamically filter these anchor tags based on the input entered in the search bar. For example, typing "Joli Cafe" should display only the link for Joli Cafe. Is there a way to achieve this functionality?

Answer №1

Utilize the <datalist> element for enhanced functionality. Connect the input field to a datalist by using the list="" attribute.

To add custom URLs to each option as data attributes (to act as anchor tags), you can then use JavaScript to retrieve the selected option and its corresponding data attribute. Once this information is obtained, you can utilize window.location with the data attribute value to navigate to the desired URL.

const searchInput = document.getElementById("searchInput");
const datalist = document.querySelectorAll('#theRestaurants > option');
const searchArray = [];

// Identify datalist options with a URL data attribute and store them in the searchArray
datalist.forEach((item) => {
  if(item.dataset.url) {
    searchArray.push(item);
  }
})

// Monitor changes in the input and loop through our search array.
searchInput.addEventListener('input', () => {
  searchArray.forEach(element => {
      // If the search input matches an option with a URL, direct user to the relevant URL
      if(searchInput.value === element.value) {
        window.location = element.dataset.url;
      }
  });
});
<div class="md-form mt-0">
  <input type="text" list="theRestaurants" name="restaurant" id="searchInput" placeholder="Search" aria-label="Search" value="">
  <datalist id="theRestaurants">
    <option value="Anafiotika Cafe-Restaurant" data-url="#acr">
    <option value="Joli Cafe" data-url="#jc">
    <option value="Five Guys Burger House" data-url="#fgbh">
    <option value="ATH Cafe Bar" data-url="#acb">
  </datalist>
</div>

Answer №2

Implement a listener using .on('input'...) that checks the search value and toggles the visibility of each <a> based on whether its content contains the search term:

$('#myInput').on('input', function() {
    let searchTerm = $(this).val()
    $('.article-link').each(function() {
        if ($(this).html().toUpperCase().includes(searchTerm.toUpperCase())) {
            $(this).show()
        } else {
            $(this).hide()
        }
    })
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="056f747060777c45362b302b34">[email protected]</a>/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffdf0f0ebecebedfeefdfabb1a9b1ae">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>

<div class="md-form mt-0">
   <input class="form-control" id="myInput" type="text" placeholder="Search" aria-label="Search">
</div>

<a class="article-link" href="https://www.anafiotika.gr/el/">Anafiotika Cafe-Restaurant</a>
<a class="article-link" href="https://www.anafiotika.gr/el/">Joli Cafe</a>
<a class="article-link" href="https://www.anafiotika.gr/el/">Five Guys Burger House</a>
<a class="article-link" href="https://www.anafiotika.gr/el/">ATH Cafe Bar</a>

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

When working on a MEAN web application, encountering HTTP responses like 403 or 500 from the Express server can sometimes go unnoticed and not be properly handled in the errorCallback function within

Within my Node web app, there is a situation where an HTTP GET request is sent in one of the Angular controllers. At the same route defined in Express, somewhere in the route logic, an HTTP 500 response (also tried 403 Error) is also being sent. However, i ...

What is the reason for the Circle to Polygon node module producing an oval or ellipse shape instead of a circle shape?

I've been experimenting with the npm package circle-to-polygon and I crafted the following code to generate a polygon that resembles a circle. const circleToPolygon = require('circle-to-polygon'); let coordinates = [28.612484207825005, 77. ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

What is the best way to bring a JavaScript file from the source file into an index.html document

I am currently in the process of developing a system using React, and as someone new to the framework, I have encountered an issue. I need to include a JavaScript file in my index.html that is located within the src folder. This js file is essential for th ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

What is the best way to conceal a ModalPopupExtender that is integrated into an ASCX user control without triggering a postback, utilizing JavaScript?

I am currently working on an Asp.net application and have encountered an issue with the ModalPopupExtender embedded within an ASCX user control. I am trying to set up a cancel button that will hide the popup without triggering a post back when clicked. He ...

Designing and implementing a platform for facilitating link posts similar to Facebook and LinkedIn

I am seeking to enhance my website by incorporating the option to like on Facebook and LinkedIn. Specifically, I want users to be able to paste a URL into a designated textbox area where it will automatically generate a content preview and provide a hyperl ...

Retrieve the current state within a redux action

Many experts recommend consolidating the logic in action creators to streamline the reducer's logic. Picture a basic (normalized) state: const initialState = { parent: { allIds: [0], byId: { 0: { parentProperty: `I'm the ...

Troubleshooting the "@material-ui/core" issue in React: Step-by-step guide

Issue with React: Unable to locate the '@material-ui/core' module in 'C:\Users\user\Downloads\inTech'22-Web Development (EDUGEN)\edu-gen\src\components' Resolution Command: To resolve, run npm in ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

What could be causing the TailWind CSS Toggle to malfunction on my local server?

While working on designing a sidebar for a ToDo page using Tailwind CSS, I encountered an issue with implementing a toggle button for switching between dark mode and light mode. In order to achieve this functionality, I borrowed the toggling code snippet f ...

Issue with Angular: PDF rendering delayed until window resize

Recently, I encountered an issue with rendering a PDF in Chrome while using an AJAX call with Angular. Strangely, the PDF would only show up in the browser if I resized the window or opened the console. Surprisingly, everything worked fine in Firefox. Jav ...

The HTML checkbox remains unchanged even after the form is submitted

On a button click, I have a form that shows and hides when the close button is clicked. Inside the form, there is an HTML checkbox. When I check the checkbox, then close the form and reopen it by clicking the button again, the checkbox remains checked, whi ...

The Ajax request fails to trigger the success function following the JsonResult response

Attempting to utilize Ajax to add a record to the database and retrieve data from JsonResult upon successful insertion leads to an error message: parseerror. Oddly enough, the record is successfully added to the DB. Below is the code for the post method: ...

New to CSS/Ruby - What causes two adjacent buttons to have varying sizes?

The varying sizes of my search and login buttons located beside each other are puzzling me. Could it be due to the fact that the search button is enclosed within a submit_tag argument while the login button is not? If this is indeed the case, how can I mak ...

Issues arising from the interaction of one DIV with another DIV

I'm having trouble positioning a menu (height = 100%) next to the logo. Essentially, when the image controls the height of the DIV (container), it seems logical that adding another DIV (menu) with height: 100% inside that DIV (container) should resul ...

Guide on organizing items into rows with 3 columns through iteration

Click on the provided JSFiddle link to view a dropdown menu that filters items into categories. Each item is stored as an object in an array for its respective category. Currently, all items are displayed in one column and I want to divide them into three ...

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...