Using jQuery to capture the anchor ID when clicked, and then extracting content from an array using JavaScript

My goal is to create an HTML anchor with a unique ID. When the user clicks the anchor, I want the ID to be passed to JavaScript using the onclick HTML attribute. Then, a JavaScript function will read the ID and display the corresponding content in a div. We are utilizing the jQuery library for this task.

This is what I have tried so far:

<a id="MyID1" onclick="var ClickVariable=this.id;return false">1</a>
<a id="MyID2" onclick="var ClickVariable=this.id;return false">2</a>

<script>
    var ClickVariable; 
    var ContentBox = []; 

                ContentBox[ClickVariable] = "Content for MyID1";

                $(ClickVariable).click(function() {
                $('.dropdown-menu-content').html(ContentBox);
            });   

    </script>

Unfortunately, the above code does not work as expected. We do have a working alternative solution, but it is not very efficient.

<a  id="MyID1">1</a>
<a  id="MyID2">2</a>

$('#MyID1').click(function() {
                    $('.dropdown-menu-content').html('Text 1');
                });
$('#MyID2').click(function() {
                    $('.dropdown-menu-content').html('Text 2');
                });

Although the above approach works, it involves a lot of repetition when dealing with a large list of elements.

Here is a link to a jsfiddle demonstrating the repetitive workaround: http://jsfiddle.net/2z7o5hn3/

Answer №1

If you want to avoid repeating code, you can use the same handler function for different elements:

//mapping id to text to display
var data = {
    'MyID1': 'Text 1',
    'MyID2': 'Text 2'
}

//shared click handler
var displayElement = $('.dropdown-menu-content');
function handleClick() {
    displayElement.html(data[this.id]);
} 

//assign click handler to each id
$.each(data, function(key, value) {
    $('#'+key).click(handleClick);
});

http://jsfiddle.net/8d6fy215/4/

Answer №2

Make sure to provide a class for all anchor tags and access them like this:

HTML:

<a id="link1" class="selectedLinks" href="#">Link 1</a>
<a id="link2" class="selectedLinks" href="#">Link 2</a>

JavaScript:

$('.selectedLinks').on('click', function(e){
  e.preventDefault();
  $('.content-area').html($(this).attr('id'));
})

Answer №3

Is this what you're looking for? => DEMO

var phrases=['Phrase 1','Phrase 2'];

$('a[class^=MyClass]').click(function() {
    $('.dropdown-list').html(phrases[$(this).text()-1]);
});

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

What is the best way to create a div that resembles a dotted line?

I have a bar chart type created using different div elements. CSS: .outer, .inner, .target { height: 14px; margin-bottom: 5px; } .outer { background-color: #cccccc; width: 200px; margin: 0 auto; position: relat ...

Tips for emphasizing active tabs in Angular 6

**I have everything displaying perfectly, but I am wondering how to highlight the active tab without using any third-party components. Any assistance would be greatly appreciated. Thank you.** <ul class="tabs"> <li [ngClass]=" {'active-tab ...

The append method contains a function

Is it possible to add a condition inside the jQuery .append() function? $.each(result, function (i, item) { $('.body-recap').append('<div class="recap event-name b-primary row">\n' + // some condition At the end of the ...

Effective HTML element placement with CSS styling

My HTML code includes a form containing a table. Take a look: This is the Code I'm Using: <html> <head></head> <body> <form onsubmit="" id="form1" action="" method="post" name="form1" style="position: rela ...

Creating a safe and secure method to access social media by utilizing the user account profile of a third-party web application

Looking to enhance a web application that features user accounts and profile pages, I am seeking advice on how to seamlessly link users' Facebook, Twitter, and LinkedIn accounts to their profiles. Additionally, I want to find a secure method for stori ...

Require assistance with a situation related to an MVC route after making a jQuery AJAX request to that route

Trying to access a basic ASP.NET MVC route is resulting in an error message: The parameters dictionary contains a null entry for parameter 'isFoo' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult Tra ...

Limiting the character count in a textarea can be achieved by implementing the 'jQuery InlineEdit' feature

Currently, I am utilizing the jquery.inlineedit.js plugin for inline editing, and one of my requirements is to limit the maximum length of text within the textarea. I have attempted to use other popular jQuery scripts for this purpose, but unfortunately, I ...

Is there a way to set a custom background image for a specific Vaadin view?

I am developing a view in Vaadin that looks something like this... public class PosAppPickerView extends VerticalLayout implements View { Everything is functioning smoothly, but I am interested in incorporating an image as the background for the body/mai ...

Button for searching through the Bootstrap navigation bar

I'm currently working on adding a search menu to the navbar in two different designs - one for screens below 767px and another for screens above 767px. Although I have been successful in expanding the search bar, I am facing issues with the correct p ...

Restoring text boxes to their original styling

I've been working on a jQuery script that scans through form input elements and turns their border color to red if they are empty. When the submit button is pressed, it reassesses the elements; this time I'm trying to revert the textbox back to i ...

Vue: The async Apollo mixin function successfully logs a value, however it ultimately returns as undefined

I've encountered numerous async/return undefined queries on this platform, but despite trying various solutions, I'm unable to make any progress. My apologies if I overlooked something obvious. In an attempt to improve reusability, I extracted a ...

I am experiencing excessive paper skipping in my printer

I have been using the 80 column dot matrix printer. However, after each printout, the paper skips two times resulting in a lot of wasted paper. How can I resolve this issue? Currently, I am only utilizing the window.print() JavaScript function. Are there ...

You can only remove one cart item at a time

I have created an online shopping website that utilizes AJAX for adding items to the cart and removing them. The strange issue I am facing is with the removal process. I can only delete one item at a time, and then have to manually refresh the page in orde ...

Alter the browser's URI without having to reload the page

Is there a way to change the browser URL (or URI) without refreshing the page using HTML5 and HTML5Shiv for IE? For example, if I am currently on http://www.example.com but want to transition to http://www.example.com/4f6gt without the need for a full pa ...

Tips for incorporating the Order By clause in intricate SQL queries to retrieve data with ASP

I am working on a complex SQL statement with multiple joins, and I need to include an ORDER BY at the end. <% Set rsProdInfo = Server.CreateObject ("ADODB.Recordset") " SELECT Company_Main.Company_Name, Company_Main.Company_Website, Pra ...

How can I choose an element based on its specific class using jQuery?

I've written some jQuery code that looks like this: jQuery(document).ready(function($){ $(".lmls").click(function(){ var groupid = $('span#gid').attr('value'); $("#otherpaths"+groupid).toggle(); // aler ...

An error occurred when trying to initialize the module dx: [$injector:modulerr]. This was due to a bad directive name, 'DOMComponent', which is invalid

Encountering an issue while running the application with the following versions: Angular: 1.6.8 JQuery: 2.2.4 Bower: 1.8.2 The screen is showing up blank. An error has been thrown: [$injector:modulerr] Failed to instantiate module ftfwebApp due to: E ...

The footer covers the content when the content fills the entire screen

I'm having trouble getting my .content_pro to stick to the top of the footer, regardless of screen resolution. When I set the height to 100%, it ends up underneath the footer. I've been struggling with this for hours but can't seem to make i ...

Passing the import name as a prop in React and combining it with the image src

I am struggling with a React component that has a prop being passed as an Import, which contains the path to an image. For this instance, the prop value is Ico1. The challenge lies in passing the prop in the img src attribute, like so: See the code belo ...

Guide to using AJAX to send a select tag value to a PHP script on the current page

Issue I am facing a problem where I need to utilize the select tag in order to choose a value and then send that value via an ajax call to a PHP script embedded within the same page. In my code, I have implemented the select tag and upon selecting a valu ...