ariefbruce ariefbruce - 1 month ago 14
Javascript Question

how to add element in jquery append

I want to add element after click button, like this:
when I click Schedule button element text will appear and when I click Agenda button element Agenda will appear one by one, but in my code when I click Agenda button when element Text > 1, element agenda will looping, my code like this:https://jsfiddle.net/vtdas7x2/1/

I want to like this:

Text 1

agenda 1

Text 2

agenda 2

Text 3

agenda 3

Answer

Move $("#add-agenda").click(function() { field_agenda = '<p>agenda '+total+'</p>'; $("#box-agenda-"+ total +"").append(field_agenda); }); out of its parent function; all scripts like :

var total = 0;
$("#add-schedule").click(function() {
    if (total<10) {
        total = total + 1;
        field_day = '<p>Text '+total+'</p><div id="box-agenda-'+total+'"></div>';
        $("#box-schedule").append(field_day);

    }
});

$("#add-agenda").click(function() {
  field_agenda = '<p>agenda '+total+'</p>';
  $("#box-agenda-"+ total +"").append(field_agenda);
});
<script src="https://code.jquery.com/jquery-2.2.1.min.js" integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00=" crossorigin="anonymous"></script>

<div id="box-schedule"></div>

<button id="add-schedule">Schedule</button>
<button id="add-agenda">Agenda</button>

Comments