Discovering the data-id value in an HTML element by clicking it with JavaScript and returning that value through a for loop

this is my unique html content

       <ul class="dialogs">
            {% if t_dialogs %}
                <li class="grouping">Today</li>
                {% for item in t_dialogs %}
                    <li class="active">
                        <a id="dialogue" class="conversation-link text-[#E8F5FC] my-2" href="{% url 'assistant:continuechat' item.pk %}" data-pk="{{item.pk}}">
                            <i class="fa fa-message fa-regular"></i> {{item.title| truncatewords:04 }}
                        </a>
                        <div class="fade"></div>
                        <div class="edit-buttons">
                            <button><i class="fa fa-edit"></i></button>
                            <button class="trash" data-id = "{{item.pk}}"><i class="fa fa-trash"></i></button>
                        </div>
                    </li>
                {% endfor %}
            {% endif %}
            // the rest of the code remains the same
   </ul>
   </div>

i've been attempting to retrieve the data-pk value when a user clicks on it using JavaScript. However, I encountered issues like 'currentTarget not defined'. I also tried different methods without success. How can I resolve this issue?

this is my custom javascript code

    const dialogLinks = document.querySelectorAll("#dialogue");
    dialogLinks.forEach(link => {
        link.addEventListener("click", getDialogueId);
    });

    function getDialogueId(e){
        var idValue = e.currentTarget.getAttribute('data-pk');
        console.log(idValue);

        if(!dialog_id){
            url = `/previous-dialog/${idValue}/`
        }else{
            url = 'start-dialog/'
        }

        return url;
    }

    $.ajax({
        type: 'POST',
        url: getId(),
        data: {
            message: usermsg,
            dialogId: dialog_id,
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
            action: 'post'
        },
        success: function(json){
            const res = json['results']
            setTimeout(() => {
                hideTyping();
                body.appendChild(messages(res, "assistant"));
                scrollToBottomOfResults();
            }, 1000);
            console.log(json)
        },
        error: function(rs, e){
            setTimeout(() => {
                hideTyping();
                body.appendChild(setBotResponse("bot"));
                scrollToBottomOfResults();
            }, 600);
            console.log(rs.error);
        },
    });

i tried other methods as well but still couldn't achieve my goal. Is there a better approach to accomplish this?

Answer №1

Your assumptions are leading you astray in this situation. First off, it is possible to have multiple elements with the same id, but this can cause issues as it will only reference the first occurrence of that id.

Secondly, it seems like you intended for the ajax request to be triggered on click, but the current code structure does not achieve that.

To address these issues, consider structuring your HTML like this:

   button.conversation-button
   button.conversation-button
   button.conversation-button

Then, add an event listener to each element with the class .conversation-button and wrap your ajax call in a function similar to what you already have:

const conversationButtons = document.querySelectorAll(".conversation-button");
conversationButtons.forEach(button => {
    button.addEventListener("click", doStuff);
});


...
function doStuff(e) {
   $.ajax( ...
     url: getUrl(e)
...
}

function getUrl(e) {
  let idValue = e.target.dataset.pk;
  let url = ...;
  ...
  return url; // 
}

This is just a rough outline to guide you in the right direction. Good luck!

Answer №2

It is not recommended to use the same id multiple times on a web page

You can utilize classes instead of ids when using querySelectorAll, such as in place of id="convers"

Include e.preventDefault() function to trigger ajax calls instead of redirecting to hyperlinks

Revise the HTML code below:

<div>
    <ul class="conversations">
        {% if t_ques %}
            <li class="grouping">Today</li>
            {% for item in t_ques %}
                <li class="active">
                    <a class="conversation-button text-[#E8F5FC] my-2" href="{% url 'assistant:continuechat' item.pk %}" data-pk="{{item.pk}}">
                        <i class="fa fa-message fa-regular"></i> {{item.title| truncatewords:04 }}
                    </a>
                    <div class="fade"></div>
                    <div class="edit-buttons">
                        <button><i class="fa fa-edit"></i></button>
                        <button class="trash" data-id = "{{item.pk}}"><i class="fa fa-trash"></i></button>
                    </div>
                </li>
            {% endfor %}
        {% endif %}
        <!-- similar structure for Yesterday, Previous 7 days, and Previous 30 days -->
    </ul>
</div>

Adjust your JavaScript code as follows

const conversationButtons = document.querySelectorAll(".conversation-button");
console.log(conversationButtons);
conversationButtons.forEach(button => {
    button.addEventListener("click", getId);
});
function getId(e){
    e.preventDefault();
    var idValue = e.currentTarget.getAttribute('data-pk');
    console.log(idValue); 
    
    if(!idValue){
        url = `/chat-previous/${idValue}/`
    }else{
        url = 'initiate-chat/'
    }
    console.log(" url ========= ");
    console.log(url);
    return url;
}

Answer №3

Make sure your IDs are unique

If you don't want to use IDs, you can try this approach

Utilize delegation and the button's class instead

It is also important to preventDefault behavior on links

document.querySelector('.chats').addEventListener('click', (e) => {
  let target = e.target.closest('.chat-button');
  if (!target) return;
  e.preventDefault(); // stop link from being followed
  const idValue = target.dataset.pk;
  console.log(idValue); //output corresponding target-id
  const endpoint = chat_id ? 'start-chat/' : `/previous-chats/${idValue}/`;
  $.ajax({
    type: 'POST',
    url: endpoint,
    ......
  });
})

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

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

Carousel Pagination: Using Titles Instead of Numbers

I am currently working on implementing a carousel pagination using the Caroufredsel plugin. I am looking to create unique custom Titles for each slide in the pagination, rather than using default numbers. My goal is to have completely different Titles fo ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Arranging sequence of jQuery functions

I have implemented a loop using jQuery that iterates through specific elements on an HTML page. During each iteration, I switch over a variable and add HTML code to particular locations. The issue arises when one of the appends requires importing another ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

Are there any superior alternatives for Android webviews?

Is there a more efficient webview option available for Android? Google's documentation advises against relying on the built-in webview object. It's puzzling that using webkit in Android is so limited compared to other mobile devices with similar ...

Nested solution object populated with promises

Looking for a solution similar to the npm libraries p-props and p-all, but with the added functionality of recursively resolving promises. const values = { a: () => Promise.resolve(1), b: [() => Promise.resolve(2)], c: { d: () =&g ...

scraping mixed content from an HTML span using Selenium and XPath

Currently, I am attempting to extract information from a span element that contains various content. <span id="span-id"> <!--starts with some whitespace--> <b>bold title</b> <br/> text here that I want to grab.... < ...

Transmitting a sequence of JSON information from php to JavaScript,

I am struggling to fetch a series of JSON data from PHP to my JavaScript file. Initially, I have multiple JSON data stored in an array in PHP, and I am echoing each one by looping through the array in my JavaScript file. <?php $result = array('{ ...

Retrieving ng-repeat $index with filtering in AngularJS controller

I am facing a challenge with my ng-repeat list and filter in AngularJS. I am unable to retrieve the visible $index value from inside my controller. Although I can display the index easily and see it change dynamically when the list is filtered, I am strug ...

What is the best way to showcase a user's input in a webpage using vanilla javascript

Struggling with creating functionalities for a simple calculator using vanilla.js. Able to display numbers on click but facing issues with multiple clicks and deletion of values. Trying to use addeventlistener but encountering a Type Error "addeventliste ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

Disable the toggling of the dropdown functionality in the bootstrap function

Recently, I made some modifications to a bootstrap navbar by transforming it into a toolbar and adjusting a dropup dropdown to include two datepicker elements. An issue arose when the dropdown would collapse upon selecting a date. To address this problem, ...

d3.json is unable to parse a value of 'Infinity

My goal is to retrieve data from an SQLite database and convert it into JSON format for use with d3.js in order to create a graph. I have successfully obtained this data in JSON format using the following URL: http://localhost:8085/SQLQuery/?date1=2019-03 ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

A guide on breaking down the ID passed from the backend into three segments using React JS

I pulled the data from the backend in this manner. https://i.stack.imgur.com/vMzRL.png However, I now require splitting this ID into three separate parts as shown here. https://i.stack.imgur.com/iy7ED.png Is there a way to achieve this using react? Bel ...

Is it possible for a website administrator to view the modifications I have made to the CSS and HTML code?

Is it possible for a website to detect any temporary changes made to their CSS or Html through developer tools, even though these changes are not permanent? ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...