user1683645
user1683645

Reputation: 1579

jquery show/hide comment reply

Hello Im trying to come up with code for showing hiding comment-id specific textareas.

I've successfully been able to assign a text area to each comment on page load and then hide and show at click. But I dont know how to hide them again. This is what I've come up with so far:

$('#show-reply-comment').each(function(){
    $(this).click(function(e){
        e.preventDefault();
        var commentid = $(this).data('commentid');
        $('#'+commentid+'').show();
        $(this).unbind('click');
        $(this).attr('id', 'hide-reply-comment');
    });
});

$('#hide-reply-comment').each(function(){
    $(this).click(function(e){
        e.preventDefault();
        var commentid = $(this).data('commentid');
        $('#'+commentid+'').hide();
        $(this).unbind('click');
        $(this).attr('id', 'show-reply-comment');
    });
});

The user should be able to have several comment-reply textareas open at the same time. Would appreciate if someone could give me a hint on how to continue.

Edit: I forgot return false; but I dont want to mess up the code

Upvotes: 0

Views: 1470

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

Like said before, #id must be unique. But its not only relative to jquery, its relative to javascript. Only css doesnt care about unique ID selector. This doesnt make it valid of course...

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382160

Instead of trying to change the id of your element and repetively bind and unbind event handlers, you could simply replace your whole code by

$('.show-hide-reply-comment').click(function(){
   var commentid = $(this).data('commentid');
   $('#'+commentid).toggle();
});

Note that I replaced the use of an Id for your button by the use of a class "show-hide-reply-comment" because an Id can be given to only one element.

Upvotes: 1

Rick Su
Rick Su

Reputation: 16440

the jQuery #id selector only return the first matched element.

you should use .class selector to have all matched elements returned.

Upvotes: 3

Related Questions