Javascript/Jquery toggle id with multiple variable

  django, javascript, jquery, toggle

this is my first question, so apologies if not written clearly.

I want to dynamically toggle a comment form after reply button is pressed. There are multiple comments (in below example three) to which a form (with different id) can be rendered separately.

I am able to do this with static id for form but not with dynamically defined id…
I have tried this static approach and this works fine.

var functs_t = {};
functs_t['fun_27'] =  $('#reply_comment_id_27').click(function() {$('#form_comment_id_27').toggle('slow');});
functs_t['fun_23'] =  $('#reply_comment_id_23').click(function() {$('#form_comment_id_23').toggle('slow');});
functs_t['fun_21'] =  $('#reply_comment_id_21').click(function() {$('#form_comment_id_21').toggle('slow');});

However, I am having struggling with a dynamic approach.

var i;
var functs = {};
for (i=0; i<comment_qs_id_list.length; i++) {
        var comment_id = comment_qs_id_list[i].toString();
        var reply_comment_id = 'reply_comment_id_'+ comment_id;
        var form_comment_id = $('#'+reply_comment_id).attr('name');
        // works >>> toggles comment 27
        functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+'form_comment_id_27').toggle('slow');});
        // does not work
        //functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+form_comment_id).toggle('slow');});
        // works >> toggles everything (but what I want is to hide initially and only toggle after clicking reply button)
        //$('#'+form_comment_id).toggle('slow');
    };

Thanks so much!

Source: Ask Javascript Questions

LEAVE A COMMENT