Sivvio
Sivvio

Reputation: 297

adding multiple buttons dynamically and add each a click handler in jquery

I'm trying to add buttons dynamically with Jquery, now for each button, I want to perform a different action, how can I achieve it? Each couple of buttons will toggle after the action is performed e.g.

I created a JSFiddle to display what I achieved so far.

var randomMeetings = Math.floor(Math.random() * 10) + 1;


for(var i = 0; i < randomMeetings; i++){
    var expandClient = '<button type="button" class="hide_client" id="_hide_'+ i +'"><i     class="fa fa-plus-square-o"></i></button><button type="button" class="show_client" id="_show_'+ i +'"><i class="fa fa-minus-square-o"></i></button>'

    $('#myButtons').append(expandClient);

}

for (var i = 0; i < randomMeetings; i++){

    $('#_show_'+i).click(function() {
        $('#_hide_'+i).toggle();       
    });
    $('#_hide_'+i).click(function() {
        $('#_show_'+i).toggle();

    });
}

Upvotes: 0

Views: 2614

Answers (2)

Sivvio
Sivvio

Reputation: 297

I edited Gaetano's answer with a single line to hide and display the button once clicked I updated the JS fiddle: JSFiddle

$(this).css('display', 'none');

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42054

This line inside a for loop is not valid:

$('#_hide_'+i).toggle();

This happens because when the for loop ends and in future a click event happens the value of the variable i is always the last.

You may change your line in (or use a closure like IIFE or let or add an element attribute):

$('#' + this.id.replace('hide', 'show')).toggle();

So that whenever you click on "_hide_0" you will toggle "_show_0" and so on.

The snippet (updated jsfiddle):

var randomMeetings = Math.floor(Math.random() * 10) + 1;


for(var i = 0; i < randomMeetings; i++){
    var expandClient = '<button type="button" class="hide_client" id="_hide_'+ i +
            '"><i class="fa fa-plus-square-o"></i>' + i + '</button>' +
            '<button type="button" class="show_client" id="_show_'+ i
            +'"><i class="fa fa-minus-square-o"></i>' + i + '</button>'

    $('#myButtons').append(expandClient);

    $('#_show_'+i).click(function() {
        var eleId = this.id.replace('show', 'hide');
        console.log("show " + eleId)
        $('#' + eleId).toggle();
    });
    $('#_hide_'+i).click(function() {
        var eleId = this.id.replace('hide', 'show');
        console.log("hide " + eleId)
        $('#' + eleId).toggle();

    });
}
.hide_client,.show_client{
    padding:3em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="myButtons">

</div>

Upvotes: 1

Related Questions