Triggering onClick events on list items to update text fields

I have been attempting to create an onClick event for li items. The goal is to change some specified text in a div to preset text using JavaScript whenever this event is activated. However, I have been unsuccessful so far. I even tried reaching out for help on reddit.

You can also find the following code snippet in a JSFiddle

<body>

<div id="header">
<h1>THE BODAK</h1>
</div>


<ul>
  <li><a href="history.php">Back</a></li>
  <li><a href="#" class="link" id="link" >Anthony</a></li>
  <li><a href="#" class="link2" id="link2" >Ben</a></li>
  <li><a href="#" class="link3" id="link3" >Jacob</a></li>
  <li><a href="#" class="link4" id="link4" >Jesse</a></li>
  <li><a href="#" class="link5" id="link5" >Karmar</a></li>
  <li><a href="#" class="link6" id="link6" >Mitchell</a></li>
</ul>
<br>
<br>
<br>
<br>
<script>

$(document).ready(function() {
    $('.link').on('click', function() {
    document.getElementsByTagName('h2')[0].innerHTML = "Anthony";
    document.getElementById("anthony").innerHTML = "Alias: Lysander Lucretius II";
    document.getElementById("anthony2").innerHTML = "A human cleric who worships Verum-Die, speaks many languages and talks much better than he hits. Has been seen with a black gem and a white gem lodged in his chest.";
    });

});

// Similar functions for other links omitted for brevity

</script>

    <h2>Anthony</h2>
    <div id="anthony" style="word-wrap: break-word; width: 100%" >Alias: Lysander Lucretius II</div></TD>
    <br>
    <div id="anthony2" style="word-wrap: break-word; width: 100%" >A human cleric who worships Verum-Die, speaks many languages and talks much better than he hits. Has been seen with a black gem and a white gem lodged in his chest.</div></TD>
    <br>

</body>

Answer №1

Your code snippet does not include jQuery, which explains why it's not functioning properly. However, there are some improvements that can be made.

Primarily, you should only utilize one document.ready handler for all your code. Additionally, adhering to the DRY (Don't Repeat Yourself) principle, you can use a single event handler for multiple elements by storing individual information in separate data attributes like this:

<ul>
    <li><a href="history.php">Back</a></li>
    <li><a href="#" class="link" id="link" data-title="Anthony" data-alias="Alias: Lysander Lucretius II" data-bio="A human cleric who worships Verum-Die, speaks many languages and talks much better than he hits. Has been seen with a black gem and a white gem lodged in his chest.">Anthony</a></li>
    <li><a href="#" class="link" id="link2" data-title="Ben" data-alias="Alias: Nishi Kani-Orc Garland-Human" data-bio="Not much is known about the rogueish character, it is known though that he is sneaky and acrobatic. He has been seen feeding a cat, and has said he will not use his shape-shifting abilities to commit crimes.">Ben</a></li>
    <li><a href="#" class="link" id="link3" data-title="Jacob" data-alias="Alias: Max" data-bio="The large half-giant is crippled and bound to a magic chair, however this giant has mastery over some sort of telekinetic arts.">Jacob</a></li>
    <li><a href="#" class="link" id="link4" data-title="Jesse" data-alias="Alias:Kuso Oma" data-bio="The age isn't the only mystery surrounding this woman, seemingly able to summon demon-like abilities at will and laughing in the face of danger. Has stated her race comes from deep underground.">Jesse</a></li>
    <li><a href="#" class="link" id="link5" data-title="Karmar" data-alias="Alias:Zota" data-bio="A human cleric who worships Verum-Die, speaks many languages and talks much better than he hits. Has been seen with a black gem and a white gem lodged in his chest.">Karmar</a></li>
    <li><a href="#" class="link" id="link6" data-title="Alias:Drudder" data-alias="Alias: Lysander Lucretius II" data-bio="This drow definitely practices some dark arts, but has already risked his life to save one of the group members. Was caught in some shady dealings with rat-folk.">Mitchell</a></li>
</ul><br><br><br><br>

<h2 id="name">Anthony</h2>
<div id="alias">Alias: Lysander Lucretius II</div><br>
<div id="bio">A human cleric who worships Verum-Die, speaks many languages and talks much better than he hits. Has been seen with a black gem and a white gem lodged in his chest.</div><br>
$(document).ready(function() {
    $('.link').on('click', function() {
        var $el = $(this);
        $('#name').text($el.data('name'));
        $("#alias").text($el.data('alias'));
        $("#bio").text($el.data('bio'));
    });
});

View working example

Answer №2

$('li').on('click', function(){
   $('h2').text($(this).find('a').text());
});

https://example.com/jsfiddle123

Whenever a li element is clicked, the text of the corresponding a tag will replace the text in the current h2 element (which makes more sense than using a div).

Answer №3

To retrieve and modify the label name for h2 as recommended by Thomas, utilize the "this" object. For handling multiple conditions instead of numerous JavaScript functions, employ a switch case or else if ladder. To assign text values within the switch case, consider using the jquery method $(#id).text(). This approach will streamline the process.

$(document).ready(function(){
    $('a').click(function(){
  var id = $(this).attr("id");
  $('h2').text($(this).text());
    if(id == "link"){
        $('h2').text($(this).text());
      $('#anthony').text("sample text for link.");
        $('#anthony2').text("detailed text.");
    }else if(id == "link2"){
        $('h2').text($(this).text());
      $('#anthony').text("sample text for link2.");
        $('#anthony2').text("detailed text.");
    }...and so forth
  })
});

Answer №4

In your JavaScript code, ensure that you write it within a single document.ready() event. Be sure to reference existing HTML tags or elements in your script.

$document.ready(function(){

  $('a').click(function(){
     document.getElementsByTagName('h2')[0].innerHTML = "Anthony";
 });  
});

-The click event should be linked to the child element of the list item being clicked, such as the anchor 'a' element. -The 'h2' tag must already exist in your HTML structure.

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 properly pass parameters?

const root = { user: (id) => { console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id))) return storage.select("users", id.id) } } Struggling to correctly pass the parameter ...

Encountering issues with an Express Server when sending multiple AngularJS Post requests. Server crashes when attempting a second post request

Since running two post requests simultaneously is not feasible on my client, I attempted to execute the second post within the .then section of the first post. This method has been successful in my previous projects. However, I encountered an issue where m ...

Tips for implementing an asynchronous function that needs to finish before proceeding in a React class component

I am facing a challenge in creating an async function within a React class component that needs to be completed before rendering. I prefer not to use lifecycle methods like componentDidMount, so I decided to utilize top-level await in the following manner: ...

Leveraging Angular js for performing operations in Putty

At the moment, we depend on Putty for connecting to the app server and checking logs. I am looking for a solution that would allow me to automate this process using angular js. Is it possible to send commands from my angular js or any other client-side a ...

The function Mediarecorder.start() is experiencing issues on Firefox for Android and is not functioning

Recently, I've been facing a peculiar issue while developing a web application. The purpose of this app is to capture about 10 seconds of video intermittently from the device webcam and then upload it to a server. For this functionality, I utilized th ...

Generatively generating a new element for the react application to be mounted on

I am looking to enhance my JavaScript application using React by creating a build. Currently, the application consists of just a single file structured as follows. This file essentially creates a div element and continuously changes the color of the text & ...

What causes the inaccessibility of methods added via decoration?

Let's say I have a Directive decorator that adds a static method called factory to its target: function Directive<T extends { new (...args: any[]): {} }>(constructor: T) { return class extends constructor { static factory(...args): ng.IDi ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

Is there a way to make Bootstrap's dark table heads hoverable without having to manually set the style?

I enjoy using hoverable tables, but I've noticed a strange behavior when including the table-dark class in my <thead>. It seems to make the header row behave like a body row, which is not what I want. Is this standard behavior and is there a way ...

Can you share the updated class name for indicating errors in input groups in Bootstrap 4?

I am currently working on creating a form. I want to implement a feature where incorrect data entered will be highlighted in red, and correct data entered will be highlighted in green. This is the code snippet from my .js file: function checkForm() { v ...

Navigating through events with jQuery

Currently, I am utilizing jQuery Steps and aiming to manage an event known as: onStepChanging. The default value for this event is function (event, currentIndex, newIndex) { return true; } I have attempted the following code snippet, but unfortunately, i ...

Validating forms using ajax, php, and mysql for seamless user input processing

I'm currently in the process of creating a login form that includes an instant email address verification feature against my database. Despite my efforts and attempts to make this functionality work, I have faced challenges in getting it to function ...

The JavaScript script that is supposed to change backgrounds is malfunctioning

Trying to develop a simple function that alters the background of a specific element when it is clicked by the user const customFunction = document.querySelectorAll("article .customClass"); const changeBackground = function() { const back ...

Checking the alignment of celestial bodies for an array of entities

Seeking to implement validation for a form featuring checkbox selections with corresponding number inputs. When a user selects a profession checkbox, they must enter the number of years of experience they have in the input next to it. The array structure i ...

Facing a dilemma: Javascript not updating HTML image source

I am facing an issue while attempting to modify the source of my HTML image element. Despite using document.getElementId('image') in my code, I am unable to make it work as intended. Surprisingly, there are no errors displayed. Interestingly, whe ...

What could be causing the href to malfunction within nav tabs in Bootstrap version 4?

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstra ...

Confirm the validity of a data point within the JSON data package

When we send a request using the HTTP GET method, the API responds with the data. I need to ensure that the values of a specific input key match exactly what was specified in the GET URL. The URL that was used for the request: https://dummy.dns.com/Wells ...

Is there a way to create dynamic documents in Firestore using Angular?

How can I use a dynamic ID to fetch the values of a document in Firestore? For example, if I have documents named document1 and document2 under the same collection, how can I specify a dynamic path with a dynamic document name to retrieve the specific do ...

Mongoose .lean() Method Causes Equality Test to Fail

In my quest to compare req.user._id with an array of ObjectIds obtained from a MongoDB query, I encountered failures in all my attempts using .includes(), as well as strict and loose equality checks. Below is a simplified version of the logic in my contro ...

The Bootstrap mixin for customizing button variants could not be located

While attempting to alter the color of a bootstrap-info button in bootstrap 4, I wrote the following: $mynewcolor:#77cccc; .btn-info { @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten ...