Home > Mobile >  How to toggle class for clicked button in for loop?
How to toggle class for clicked button in for loop?

Time:10-05

trying to add post to bookmark. posts are on home page with in for loop. I have trouble getting toggle class while clicking on add bookmark button for individual post.

Django view

@login_required
def add_post_bookmark(request):
    ''' add post to bookmark '''
    if request.POST.get('action') == 'post':
        result = ''
        is_bookmark = False
        id_ =  request.POST.get('id')
        post = Post.objects.get(id=id_)
        if post.bookmarks.filter(id=request.user.id).exists():
            post.bookmarks.remove(request.user)
            is_bookmark = False
            post.save()
            result = post.get_bookmarks_count()
        else:
            post.bookmarks.add(request.user)
            is_bookmark = True
            post.save()
            result = post.get_bookmarks_count()

        return JsonResponse({'result': result, 'bookmark_count': post.bookmarks.all().count(), 'post_id': id_, 'is_bookmark': is_bookmark})

Ajax

 // bookmarks posts
    $(document).on('click', '#bookmark_add', function (e) {
        e.preventDefault();
        var bookmarkCount;
        var id = $(this).data("id");
        $.ajax ({
            type: 'POST',
            url: '{% url "users:add-post-bookmark" %}',
            data: {
                'id': id,
                csrfmiddlewaretoken: '{{ csrf_token }}',
                action: 'post'
            },
            success: function (response) {
                $('#' id).empty().append(response['bookmark_count']);
                console.log(response);
                this_id = $(this).data("data-id");  //("id")
                console.log(this_id);  // undefined
                $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark");
            },
            error: function (xhr, errmsg, err) {
                console.log("Error bookmarking post!");
            }
        });
    })

index.Html

    <span id="{{post.id}}" class="bookmark_coun text-muted">{{ post.get_bookmarks_count }}</span>
    {% if request.user.is_authenticated %}
        {% if request.user not in post.bookmarks.all %}
          <button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="far fa-bookmark fa-lg"></i></button>
        {% else %}
          <button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="fad fa-bookmark fa-lg"></i></button>
        {% endif %}
   {% else %}
    <a href="{% url 'users:register' %}" id="bookmark_add" class="bookmark"><i class="far fa-bookmark fa-lg"></i></a>
   {% endif %}

Problem: Every time I'm trying to bookmark it's toggling other element. I tried get element by id but it's not working that way too.

tried this but still nothing:

this_id = $('#bookmark_add').data("id");  //("id")
                console.log(this_id);
                if (this_id === id) {
                    $("button[this_id]").find('i').toggleClass("fad fa-bookmark far fa-bookmark");
                }

CodePudding user response:

I think you are in wrong way to get the id of the button. Using the onclick method of jquery, you may get the id of the clicked button using attr method, like this

$('.bookmark').click(function() { 
    var id = $(this).attr('id');
});

$('.bookmark').click(function() { 
      console.log($(this).attr('data-id'));
    console.log("BEFORE: "   $(this).find('i').attr('class'));
    $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark");
    console.log("AFTER: "   $(this).find('i').attr('class'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="bookmark_add" class="bookmark" name="bookmark" data-id="1">
    <i class="far fa-bookmark fa-lg"> Test 1</i>
 </button>
 
 <button id="bookmark_add" class="bookmark" name="bookmark" data-id="2">
    <i class="fad fa-bookmark fa-lg"> Test 2</i>
 </button>

Even rather than getting id, you may toggle the class of your i element inside the above click event definition, like this

$('.bookmark').click(function() { 
    $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark");
});

Kindly let me know if this works.

  • Related