1

I was able to generate a new <div> to another <div> and those new <div> have a custom id generated by a counter, i need the code to be able to add new <div> to those that where generated.

Code :

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
    <script>
        var counter = 1

        $(document).ready(function () {
            $("#BtnRev").click(function () {
                $("#" + "div" + counter).remove();
                counter = counter - 1;
                if (counter <= 0)
                {
                    counter = 1;
                }
            });


                $("#BtnAdd").click(function () {
                    $("#divMaster").append("<div id='div" + counter + "' class='well'><h4><b>" + counter + ". </b>" + StepTitle.value + "</h4><p>" + Description.value + "</p><button type='button' ID='Btn" + counter + "' class='btn btn - basic'>Add</button></div>");
                    counter = counter + 1;
                    //StepTitle.value = "";
                    //Description.value = "";
                });

            /*$("#" + "Btn" + counter).click(function () {
                $("#" + "div" + counter).append("<div id='div" + counter + 1 + "' class='well'><h4><b>" + counter + ". </b>" + StepTitle.value + "</h4><p>" + Description.value + "</p><button type='button' ID='Btn" + counter + "' class='btn btn - basic'>Add</button></div>");
            });*/
        });
    </script>

    <br />
    <button type="button" ID="BtnAdd" class="btn btn-basic">Add</button>
    <button type="button" ID="BtnRev" class="btn btn-danger">Remove last step</button>
    <hr />
    <label for="StepTitle">Title: </label>
    <input type="text" id="StepTitle" class="form-control" placeholder="Title..." />
    <label for="Description">Description: </label>
    <textarea rows="5" id="Description" class="form-control"></textarea>
    <hr />
    <script src="Test2.js"></script>
    <div id="divMaster" class="well">
        <h4>This is how the steps will look like: </h4>
    </div>

I've tried this:

$("#" + "Btn" + counter).click(function () {
$("#" + "div" + counter).append("<div id='div" + counter + 1 + "' class='well'><h4><b>" + counter + ". </b>" + StepTitle.value + "</h4><p>" + Description.value + "</p><button type='button' ID='Btn" + counter + "' class='btn btn - basic'>Add</button></div>");
});

But it's not working, the expected output should be several <div> within themselves all of them generated by jquery, if you guys have any other methods i'll be more than glad to check them out, thanks in advance!

  • Use classes and don't worry about using ID. then when click the `basic` button you append to it's parent by starting at `this` in the event handler. `$(this).closest('.well').append('....')` – charlietfl Nov 12 '19 at 23:53

1 Answers1

0

Try using:

$("#divMaster").on("click", "#"+"Btn"+counter, function(){
// your code here
});
Giorgio.dev
  • 131
  • 2
  • 12