user1391778
user1391778

Reputation: 75

How to get Jquery to Show/Hide Dynamic Div Element?

I want to use JQuery replicate the following javascript code so the page doesn't have to refresh. The main issue I'm having with Jquery is that the divs I want to select vary based on the comment id of which there could be hundreds. Any help or suggestions are very much 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>

Upvotes: 4

Views: 8664

Answers (4)

Tats_innit
Tats_innit

Reputation: 34107

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

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

code

toggle_visibility = function (id){

   var e = $("#"+id);
   e.toggle();
}​

Upvotes: 3

The System Restart
The System Restart

Reputation: 2881

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();
}

Upvotes: 1

dku.rajkumar
dku.rajkumar

Reputation: 18578

if i had to do this, i would it in much easier way like 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();
 });

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

Upvotes: 0

Sampson
Sampson

Reputation: 268424

Since you're using jQuery, use $.toggle() instead:

$( '#' + id ).toggle();

Upvotes: 2

Related Questions