How to make jQuery show / hide dynamic div element?

I want to use jQuery to replicate the following javascript code so that the page does not refresh. The main problem I am encountering in jQuery is that the divs I want to select depends on the comment identifier, which can be hundreds. Any help or suggestions are greatly appreciated!

<head> <script type="text/javascript"> <!-- function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'visible'; else e.style.display = 'block'; } //--> </script> </head> <body> {% for comment in comments %} <a href="#" onclick="toggle_visibility('make_reply_{{comment.id}}');">Reply</a> <div id="make_reply_{{comment.id}}"> <form name="titleform" action="/{{slug}}/reply/" method = "post"> <input type="hidden" name="id" value="{{comment.id}}"</input> {% csrf_token %} <textarea name = "comment" value="" rows="7" cols="50"></textarea><br> <input type="submit" value="Submit"/> </form> </div> {% endfor %} </body> 
+4
source share
4 answers

HIya demo http://jsfiddle.net/gpwnn/

API Link: http://api.jquery.com/toggle/

the code

 toggle_visibility = function (id){ var e = $("#"+id); e.toggle(); }​ 
+3
source

Since you are using jQuery, instead of $.toggle() :

 $( '#' + id ).toggle(); 
+2
source
 function toggle_visibility(id) { var $e = $('#' + id); if($e.is(':visible')) $e.hide(); else $e.show(); } 

or just $e.toggle();

 function toggle_visibility(id) { var $e = $('#' + id); $e.toggle(); } 
+1
source

if I had to do this, I would make it a lot easier, as shown below:

HTML:

  {% for comment in comments %} <div id="{{comment.id}}"> // this div will separate each iterate elements <a href="#">Reply</a> // no inline method required in jquery <form name="titleform" action="/{{slug}}/reply/" method = "post"> <input type="hidden" name="id" value="{{comment.id}}"/> <textarea name = "comment" value="" rows="7" cols="50"></textarea><br> <input type="submit" value="Submit"/> </form> </div> {% endfor %} 

JQuery

  $('a').click(function(){ $(this).next('form').toggle(); }); 

script: http://jsfiddle.net/VjthL/2/

0
source

Source: https://habr.com/ru/post/1412224/


All Articles