Discovering the current active link and anchor tag details using jQuery in an unordered list

I am currently utilizing jQuery to work with 4 anchor tags inside an unordered list, and I would like to be able to determine the "current active link" when a user performs a search. This way, I can execute my query based on the selected anchor tag. How can I achieve this? Here is the code snippet:

<ul class="categorisbtn" id="categorisbtn" name="categorisbtn">
              <li ><a href="javascript:void(0);" class="nav-link activelink" data-tagc="Company"><img src="images/inner-img/Company-Report.svg" alt="img" class="img-fluid"> Company Report</a></li>
              <li ><a href="javascript:void(0);" class="nav-link" data-tagc="StateR"><img src="images/inner-img/State-Report.svg" alt="img" class="img-fluid"> State Report</a></li>
              <li ><a href="javascript:void(0);" class="nav-link" data-tagc="BasinR"><img src="images/inner-img/Basin-Report.svg" alt="img" class="img-fluid"> Basin Report</a></li>
              <li ><a href="javascript:void(0);" class="nav-link" data-tagc="SectorR"><img src="images/inner-img/Sector-Report.svg" alt="img" class="img-fluid"> Sector Report</a></li>
            </ul> 

Here is the code I have tried:

$(document).on("keyup", "#search_param", function () {

              var interest = $('ul#categorisbtn').find('li.activelink').data('interest');
            alert(interest);
 });
    

Answer №1

When the page loads, you can include a script in the head section to set an active link:

<script type="text/javascript">

$(document).ready(function(){
  $('ul.categoriesbtn li a').click(function(){
        // remove all classes
        $('li a').removeClass('activelink');
        // add class to the selected element
        $(this).addClass('activelink');
    });
});

</script>

Next, in your search function:

$(document).on("keyup", "#search_param", function () {

  var interest = $('ul.categoriesbtn').find('li>a.activelink').data('tagc');
  alert(interest);
 });

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

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Using the jQuery-UI vertical navigation menu in conjunction with the theme switcher

I am looking to create a vertical navigation menu that is compatible with jQuery UI ThemeRoller. How can I define the styles for my menu? I typically build menus dynamically using PHP code, as shown below: $menu = '<ul>'; foreach ($items a ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

Not enough test coverage with Jest

Here is the code snippet I am working with: <ReturnToLastSearch href={'/listings'} onClick={(e): void => { e.preventDefault(); router.back(); }} /> The function ReturnToLastSearch( ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...

Generate a collection of div elements as child nodes

I'm working on a project where I have multiple rows with input fields. My goal is to create an array for each row that contains the values of the inputs. For example, if I have 3 rows and the values of 'input1' are 1, 'input2' are ...

Are ES6 arrow functions not supported in IE?

When testing this code in my AngularJs application, it runs smoothly on Firefox. However, when using IE11, a syntax error is thrown due to the arrows: myApp.run((EventTitle, moment) => { EventTitle.weekView = event => \`\${moment(event.s ...

What is the best way to destructure an array enclosed within the Promise keyword in JavaScript?

Currently, I am attempting to extract information from a PSQL table using the following code: async function requestData() { var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."Use ...

When scrolling down, the popup window shifts its position

I have implemented a popup window which displays a list on hover. It works perfectly on the default page, but when I scroll down, the popup also moves with the scrollbar. Below is the HTML code that creates the hidden popup list initially and shows it on ...

Ways to ensure that the $http.post api call waits for the response to be fully prepared

Below is the JavaScript code that I am using. When I click the button, it calls the function btnInitiateAPICall() which makes the first API call to get the number of users. However, my code does not wait for the first API call to finish before moving on ...

Inserting multiple rows in MySql using JavaScript through a URL pathUnique: "

Hello there! I am currently attempting to send an array of objects to my MySql Database via an API endpoint. Below is the code snippet from my API: app.get("/orderdetails/add", (req, res) => { const { item__, Qty_Ordered, Unit_Price, ...

In internet explorer with AJAX, the UI is refreshed by Javascript only when an alert() function is triggered

Having an issue in Internet Explorer, works perfectly in Firefox. There is a javascript function that updates the UI (screen content) before an AJAX call. However, it does not update the UI unless an alert box prompt is used. Without the alert box, the UI ...

What could be causing my getTimestamp() method to malfunction in PHP?

My table has a column of type timestamp where the data stored appears like this: https://i.stack.imgur.com/NLbip.png I am trying to make a simple select query to determine if there is a date between a specified start date and end date. This is the code ...

An unexpected issue occurred during runtime, specifically a TypeError stating that the function posts.map is not

Currently, I am diving into the world of nextjs and decided to follow a tutorial on building a Reddit clone that I stumbled upon on Youtube. However, I encountered a persistent issue: posts.map is not a function I would appreciate any assistance you can o ...

Trouble Ensues When Using Two Jquery Datatables with the Same Class

I am facing an issue with two jQuery datatables that have the same class names. The search functionality works in one table but not in the other. I need some help reviewing my code to figure out how to fix this. jQuery $('.dataTable th.searchClass&a ...

Obtaining the uploaded file in the Controller that was uploaded using the yiihelpersHtml::fileInput method in Yii2

I included the following code in my form: <?php echo Html::fileInput('imageFile', '', array('id' => 'contentForm_imageFile' )) ?> Then, I attempted to retrieve the file in the controller using this code: ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

Error: Unable to execute setState in React Native

Why am I receiving an error stating that this.setState is not a function? I'm having trouble understanding why my code isn't working as expected. import React from 'react'; import axios from 'axios' import { StyleSheet, Text ...

JavaScript encountered an issue: Uncaught ReferenceError - 'userNumber' is undefined at line 43

I'm currently working on a JavaScript guessing game where I've already set up the necessary functions. However, I keep encountering an error. An error in my JavaScript code is causing a ReferenceError: userNumber is not defined on line 43 to b ...