skip to Main Content

this is my html

       <ul class="conversations">
            {% if t_ques %}
                <li class="grouping">Today</li>
                {% for item in t_ques %}
                    <li class="active">
                        <a id="convers" 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 %}
            {% if y_ques %}
                <li class="grouping">Yesterday</li>
                {% for item in y_ques %}
                    <li>
                        <a id="convers" 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 %}
            {% if s_ques %}
                <li class="grouping">Previous 7 days</li>
                {% for item in s_ques %}
                    <li>
                        <a id="convers" 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 %}
            {% if more_s_ques %}
                <li class="grouping">Previous 30 days</li>
                {% for item in more_s_ques %}
                    <li>
                        <a id="convers" 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 %}
        </ul>
   </div>

i’ve been trying to get the value of any data-pk when being clicked on using javascript but can’t seem to achieve that. This kept saying currentTarget not defined and when i replaced it with target, it says the same thing. then if i replace it it with document.querySelector("#convers"), it just give the first value, regardless of which is clicked on

this is my javascript

    const conversationButtons = document.querySelectorAll("#convers");
    conversationButtons.forEach(button => {
        button.addEventListener("click", getId);
    });

    function getId(e){
        var idValue = e.currentTarget.getAttribute('data-pk');
        console.log(idValue); //output corresponding target-id

        if(!chat_id){
            url = `/chat-previous/${idValue}/`
        }else{
            url = 'initiate-chat/'
        }

        return url;
    }

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

i used other methods like

    const getId = () => {
        console.log(document.querySelector(".conversation-button").getAttribute('data-pk'))
         if(!chat_id){
             url = `/chat-previous/${document.querySelector(".conversation-button").getAttribute('data-pk')}/`

      
         }else{
             url = 'initiate-chat/'
    
         }
    
        return url;
    }

    conversationButtons.forEach(button => {
       button.addEventListener("click", getId);
        console.log(button.getAttribute('data-pk'));
    });

still couldn’t get what i really want. is there a way i can achieve this?

3

Answers


  1. You must have unique IDs

    To not even need IDs, you can do this

    Delegate and use the class of the button

    document.querySelector('.conversations').addEventListener('click', (e) => {
      let tgt = e.target.closest('.conversation-button');
      if (!tgt) return;
      const idValue = tgt.dataset.pk;
      console.log(idValue); //output corresponding target-id
      const url = chat_id ? 'initiate-chat/' : `/chat-previous/${idValue}/`;
        $.ajax({
          type: 'POST',
          url: url,
          ......
    })
    
    Login or Signup to reply.
  2. You are making multiple wrong assumptions, number one is that you cannot have multiple elements with the same id, it will lead to the exact behaviour that u describe "it takes the first occurance id"

    second thing is that you probably want to make the ajaxrequest on click, the way you build your code it does´nt do that.

    To adress the issues generate the html like following

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

    then add a eventlistener to all elements with the class .conversation-button, and wrap your ajax call into a function, mostly what u 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; // 
    }
    

    just some pseudo code to let u get an idea, good luck 🙂

    Login or Signup to reply.
  3. In web page you can not use same id multiple times

    You can use class for querySelectorAll instead of id="convers"

    Add e.preventDefault() function to call ajax instead of redirect to hyper link

    change the html code as 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 %}
            {% if y_ques %}
                <li class="grouping">Yesterday</li>
                {% for item in y_ques %}
                    <li>
                        <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 %}
            {% if s_ques %}
                <li class="grouping">Previous 7 days</li>
                {% for item in s_ques %}
                    <li>
                        <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 %}
            {% if more_s_ques %}
                <li class="grouping">Previous 30 days</li>
                {% for item in more_s_ques %}
                    <li>
                        <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 %}
        </ul>
    </div>
    

    And change your javascrpt code as below

    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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search