Tom Higgins Tom Higgins - 2 months ago 7
HTML Question

How can I use "for loops" in Jquery without this mistake?

Here's the problem:
I have a simple unordered list of posts. Each post is truncated (250 chars), but should expand when clicked (Using .replaceWith). What I'm trying to do is replace the truncated Post.content with the "untruncated" Post.content. When I try this, the click returns the content of all the Posts in my list. I only want the content of the Post that I am clicking. Here's the relevant code:

<ul>

{% for post in object_list %}<tr class="{% cycle 'row1' 'row2' %}"></tr>
<div class="panel panel-default col-sm-offset-1 col-sm-8">
<p><h4><B><a class="title" href="/posts/{{ post.id }}/">{{post.title }}</a></B></h4></p>
<p style="color:gray">Author:
<a style="color:darkgray" href="{% url 'accounts:profile' %}"> <span class="link">{{ user.first_name }} {{ user.last_name }}</span></a></p>
<hr style="">
<div class="post" >
<h5 style="color: rgba(101, 106, 106, 1)">{{post.content|truncatechars:250 }}</h5>
</div>
<div class="expandContent">
<button class="btn btn-primary btn-sm">Read</button>
</div>
<br>





<br>
<br>
<div class="content">
<p>{{ post.content }}</p>
</div>
</div>



<br>


{% endfor %}

</ul>


Above is my basic list. Here is the JS that should expand the Post.content:

<script src="{% static 'posts/jquery-3.1.1.js' %}"></script>
<script type="text/javascript">
$(".expandContent").click(function(){$(".post").replaceWith($('.content'));
});


</script>


If any more information or code would be helpful, please let me know. If it's at all relevant, this project is on Django 1.10. Thank you!

Answer

You can do something like this

<ul>

    {% for post in object_list %}<tr class="{% cycle 'row1' 'row2' %}"></tr>
        <div class="panel panel-default col-sm-offset-1 col-sm-8">
    <p><h4><B><a class="title" href="/posts/{{ post.id }}/">{{post.title }}</a></B></h4></p>  
                    <p style="color:gray">Author:
            <a style="color:darkgray" href="{% url 'accounts:profile' %}"> <span class="link">{{ user.first_name }} {{ user.last_name }}</span></a></p>
        <hr style="">
        <div class="post" >
            <h5 style="color: rgba(101, 106, 106, 1)">{{post.content|truncatechars:250 }}</h5>
        </div>
            <div class="expandContent">
            <button class="btn btn-primary btn-sm" onclick="replace("content-1">Read</button>
            </div>
            <br>





        <br>
        <br>
        <div class="content" id="content-1">
            <p>{{ post.content }}</p>
        </div>
        </div>



        <br>


    {% endfor %}

</ul> 

and in the replace function you can getelementbyid and display it.