jquery - Multiple toggle buttons with the same class -
i'm putting simple blog, , 1 of features trying implement comment/reply section on each post. in post view have foreach loop prints comments post.
@foreach (var comments in model.post.comments) { if (comments.replytoid == 0) { <p>@comments.body <span><a href="#" class="togglereply">reply</a></span></p> <div id="replytextbox" style="display:none"> @using (html.beginform("reply", "comment", formmethod.post)) { <input type="hidden" name="postid" value="@model.post.postid" /> <input type="hidden" name="commentid" value="@comments.commentid" /> <input type="text" name="body" id="commentbody" /> <input type="submit" value="submit" /> } </div> } foreach (var reply in model.post.comments) { if(reply.replytoid == comments.commentid) { <ul> <li>@reply.body</li> </ul> } } } i have if statement checks database see if comment new comment, or reply comment. each new comment contains reply button allow user reply comment. added jquery button hide or show reply textbox.
here jquery code:
@section scripts { <script type="text/javascript"> $(document).ready(function () { $('.togglereply').click(function () { $('#replytextbox').toggle(); }); }); </script> } the problem i'm having because of dynamic nature of these reply textboxes, first button seems reveal textbox. when click on other preceding reply buttons, textbox first reply button affected.
apologies less concise explanation.
use .on() instead:
<script type="text/javascript"> $(document).on('click', '.togglereply', function () { $('#replytextbox').toggle(); }); </script> this subscribe click event of dom elements matching selector (#togglereply) if don't exist when dom loaded added subsequently. reason don't need wrap code in $(document).ready() shown in code sample.
also notice might end duplicate ids here results on invalid dom:
<input type="text" name="body" id="commentbody" /> same #replytextbox.
you might need fix this:
@foreach (var comments in model.post.comments) { if (comments.replytoid == 0) { <p>@comments.body <span><a href="#" class="togglereply">reply</a></span></p> <div class="replytextbox" style="display:none"> @using (html.beginform("reply", "comment", formmethod.post)) { <input type="hidden" name="postid" value="@model.post.postid" /> <input type="hidden" name="commentid" value="@comments.commentid" /> <input type="text" name="body" /> <input type="submit" value="submit" /> } </div> } foreach (var reply in model.post.comments) { if (reply.replytoid == comments.commentid) { <ul> <li>@reply.body</li> </ul> } } } and adapt script accordingly of course:
<script type="text/javascript"> $(document).on('click', '.togglereply', function () { $(this).next('.replytextbox').toggle(); }); </script>
Comments
Post a Comment