Dafom Chollom
Dafom Chollom

Reputation: 25

how to change multiple image src using jquery in django

i'm trying to change the image src for each comment depending on the first letter found in the users name

{% for comment in articles.comments.all %}
      <div class="comments py-2 my-3">
           <div class="comments-img-wrapper">
                <img src="" class="comment-image" alt="">
           </div>
           <div class="comments-details">
                 <h5 class="comment-user-name">{{comment.user}} <span class="float-right date">{{comment.created}}</span></h5>
                 <p>{{comment.body}}</p>
            </div>
       </div>
       {% empty %}
       <p>there are no comments</p>
{% endfor %}

and the jquery code i'm using is this

<script>
    $(".comment-image").each(function(){
        username = $('.comment-user-name').text();
        usernameFirstletter = username.charAt(0).toUpperCase();
        console.log(usernameFirstletter)
        $(".comment-image").attr('src', '/static/img/avatars/' + usernameFirstletter + '.svg');
      });
</script>

but for some reason it keeps repeating the image of the first ccomment for the remaining comments, can anyone help

Upvotes: 2

Views: 371

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115272

You are using $('.comment-user-name').text() to get the username which always returns text content first among the collection independent of the current img tag within the callback.

So you need to get .comment-user-name related to the current img tag, for that get common parent(.comments) and get it. In addition to that, you have to update src attribute of the current element instead of $(".comment-image").attr(...) which updates attribute of all elements.

<script>
    $(".comment-image").each(function(){
        let username = $(this).closest('.comments').find('.comment-user-name').text();
        let usernameFirstletter = username.charAt(0).toUpperCase();
        console.log(usernameFirstletter)
        $(this).attr('src', '/static/img/avatars/' + usernameFirstletter + '.svg');
      });
</script>

You can make it even simpler by using attr() method with a callback which iterates over elements internally and updates with the returned value of callback.

<script>
    $(".comment-image").attr('src', function(){
        let username = $(this).closest('.comments').find('.comment-user-name').text();
        let usernameFirstletter = username.charAt(0).toUpperCase();
        return '/static/img/avatars/' + usernameFirstletter + '.svg';
      });
</script>

Upvotes: 2

Related Questions