Search code examples
javascripthtmlloopstwigchat

How to change contents on clicking the selected div using Javascript?


I am new to Javascript. I wish to change the contents of div on selecting a particular div element. If I select a div, the text associated with that div contents only should display. I am using a loop to display the contents. It's like a chat application. If a user clicks on a contact the messages associated with that user should display. I am using a loop to display messages and users.

What I have tried is:

Twig code:

    {% set msg = query().from('messages').get() %}
    {% set to_add =to_name %}
{% set to_details = query().from('users_users').where('id', to_add).get() %}
    <div class="container">
               <h3 class=" text-center">Messaging</h3>
<div class="messaging">
      <div class="inbox_msg">
        <div class="inbox_people">
          <div class="headind_srch">
            <div class="recent_heading">
              <h4>{{auth_user().first_name}}</h4>
            </div>
            <div class="srch_bar">
              <div class="stylish-input-group">
                <input type="text" class="search-bar"  placeholder="Search" >
                <span class="input-group-addon">
                <button type="button"> <i class="fa fa-search" aria-hidden="true"></i> </button>
                </span> </div>
            </div>
          </div>
          <div class="inbox_chat">
              {% set newArray = [] %}
              {% for msg in msg_details %}
              {% if msg.to_name not in newArray %}

             
            <div class="chat_list active_chat"  onclick=viewMessage(this)>
              <div class="chat_people">
                <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
                <div class="chat_ib">
                  <h5>{{msg.to_name}} <span class="chat_date">{{msg.time}}</span></h5>
                  
                </div>
              </div>

        </div>
        {% set newArray = newArray|merge([msg.to_name]) %}
            {% endif %}
            {% endfor %}

      </div>
    </div>
    <div class="mesgs">
      <div class="msg_history">
        <div class="incoming_msg">
            
          <div class="incoming_msg_img">
              <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> 
            </div>
          <div class="received_msg">
            <div class="received_withd_msg">
              <p>{{msg.message}}</p>
              <span class="time_date">{{msg.time}}</span></div>
          </div>
        </div>
        <div class="outgoing_msg">
          <div class="sent_msg">
            <p></p>
            <span class="time_date"></span> </div>
        </div>
        
       
        
      </div>
    
    </div>
  </div>
  
  

</div></div>

Javascript code:

    <script>
    function copyText(elementId){    
var x = document.getElementById(elementId).textContent;
 if(document.getElementById('select-text').value.length == 0)
         {
            document.getElementById("btn").disabled = false; 
         document.getElementById(elementId).style.backgroundColor = "lightblue";
          document.getElementById('select-text').focus();
          document.getElementById('select-text').value += x;
         }
     else{
        
         document.getElementById('select-text').readOnly = true;
     }
}
</script>

What my output looks like

Output

My output shows all the messages, I want to show only the particular user message. How to do so?

What my table looks like:

Table


Solution

  • First of all you have to fetch the data from your table using a query something like to ensure you will get one record from each from_id.

    SELECT * FROM msg GROUP BY from_id;
    

    Then you can loop in twig to create the left side elements like,

    {% for distinctMsg in distinctMsgs %}
    <div class="chat_list active_chat"  data-userId="{{ distinctMsg.fromId }}">
        <div class="chat_people">
           <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
           <div class="chat_ib">
               <h5>{{distinctMsg.to_name}} <span class="chat_date">{{distinctMsg.time}}</span></h5>
           </div>
         </div>
    </div>
    {% endfor %}
    

    Then in your javascript:-

    $(".chat_list").on("click", function(){
    
        // have a look here https://stackoverflow.com/questions/5309926/how-can-i-get-the-data-id-attribute
        var userId = $(this).data( "userId" );
    
        // Maybe display a loading icon in the right side div
    
        $.ajax({
           type: "POST",
           url: "/api/msg/user/history", // your controller url
           dataType: 'json',
           headers: {
              // if you have any headers to set
              "Authorization": "Bearer {{ token }}"
           },
           data:{
              "userId" : userId
           }
        })
        .done(function (response) {
             
            // stop displaying the loading icon
            // process the response and display message history in right side
         
        })
        .fail(function (xhr, status, error) {
            // show proper error message
        });
    
    });
    

    NOTE: You will have to have jQuery in your page for Ajax functions to work.