0

The idea is that I would like to add a text box in each div, that I have created dynamically.

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>trial </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--bootstrap setup-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="trial.js"></script>
    
  </head>

  <div>
    <p> Title</p>
  </div>

  <div>
    <button class = "btn_add">Add  </button> 
  </div>
  <!-- level container-->
  <div id = "container">

  </div>
  <!--stuff container -->
  <div id="random_container">                
  </div>

  </body>
</html>

JS

$(document).ready(function () {

  var i = 1;
  $(document).on('click', '.btn_add', () => {
    let newElement  = document.createElement('div');
    newElement.setAttribute("id", "level_" + i);
    newElement.setAttribute("class", "panel");
    $('#container').append(`<div id="title">\
      Level ` + i +`
      </div> \
      <div>\
      <button id =btnadd_`+ i +` class="btn_addStuff"> Add Stuff </button>
      </div>`);
        
    $('#container').append(newElement);
    
        
    i = i + 1; 
  });
  
  $(document).on('click', '.btn_addStuff', () => {

    /**let element = document.getElementById(div = "level_"+i);
    element.append(`<div id="card"> \
      <textarea placeholder="Title" type="text" maxlength="10" rows="1">Stuff</textarea> \
      </div>`);
    $('random_container').append(element); */

    $('#random_container').append(`<div id="card"> \
      <textarea placeholder="Title" type="text" maxlength="10" rows="1">Stuff</textarea> \
      </div>`
    );
  });
    
});

My idea is that if I click the button add, I should have a div where there is level 1 and the button add stuff. Which it works.

For example, if I click 3 times, the button add, I should have three div, which each contains a button "add stuff" and the name level. What I would like to do, is if I click the button add stuff, it should appear a text box. The problem that I am having with my code, is that I am not able to have the text box in the right position. If I am in the level one and I click 2 times the button add stuff, I should get two text boxes in the level one, and if I decide to click 3 times on the level 2 to get 3 boxes, I should get 3 text boxes.

Instead, what happens, it's that I am having the text boxes only in one level.

What I thought is to try to get the id in the addstuff button and then try to append the code and then add everything in the random_container, but I can't get an element that has created dynamically?

Hope the question is clear.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Does this answer your question? [Adding div element to body or document in JavaScript](https://stackoverflow.com/questions/15741006/adding-div-element-to-body-or-document-in-javascript) – Józef Podlecki Dec 19 '20 at 16:28
  • You're adding multiple elements with `id="title"` to your document, but an `id` is supposed to be unique. As for adding the textbox to the right div, you can use something like, I guess? https://jsfiddle.net/zo62fn7h/ –  Dec 19 '20 at 16:35
  • @JózefPodlecki, nope. Is my question not clear? Should I try to explain in a different way? –  Dec 19 '20 at 16:35
  • @ChrisG , the title is something that I will change with json, so the id title will change. but in the mean time, I would like to have the text boxes in the "right" position. i clicked twice on add, so i have two levels. each of these levels, have a button called add stuff and the name of the level. i am on level one, i click the button add stuff, twice I should see 2 text boxes in the level one. –  Dec 19 '20 at 16:38
  • I see, isn't that exactly what my fiddle does though? –  Dec 19 '20 at 16:42
  • @ChrisG, yes it does. But I don't understand why using the closest? Thank you. –  Dec 19 '20 at 16:45
  • I believe you should store i as a global variable, and every time the button add is clicked, you should increase i using i++;. Then, you would add a class to all the textareas to position them correctly. – Love2Code Dec 19 '20 at 16:53
  • As descibed [here](https://api.jquery.com/closest/), I'm going up from the button to the level div (which is the one I want to append the textarea to) also note that I'm not using an arrow function as click handler; that way `$(this)` is the button jQuery object. –  Dec 19 '20 at 16:57

2 Answers2

1

Seeing as you're using jQuery, you're life will be a lot easier using jQuery to create the new elements:

var i = 1;

$(".btn_add").on('click', () => {
    // Create Main Div
    var mainDiv = $("<div />").prop("id", "level_" + i).addClass("panel");
    // Create Title Div
    var divTitle = $("<div />").prop("id", "title_" + i).html("Level " + i);
    // Create Button to add cards inside this div
    var divButton = $("<button />")
        .prop("id", "btnAdd" + i)
        .html("Add Stuff")
        .on('click', () => {
             // Get number of cards already in this div so we can generate unique id
             var cardCount = $("#level_" + i).find(".card").length;
             // create the Card
             var card = $("<div />").prop("id", "card_" + cardCount + 1).addClass("card").html("I am a card");
             // Put the card in this div
             $("#level_" + i).append(card);
        }));

    // Put it together
    mainDiv.append(divTitle).append(divButton);

    // Put it in the container
    $("#container").append(mainDiv);

    // Increment the counter
    i++;
});

Note: Your code will try to create elements with the same id in places. Can't do that.

Neil W
  • 7,670
  • 3
  • 28
  • 41
  • Where is `i` defined/incremented ? – Louys Patrice Bessette Dec 19 '20 at 16:47
  • Hey man! I've just focused on helping you with the problematic area of the main button click and building your controls. Am sure you can take my input from here on. PS. You'll might want to declare your var i = 1 outside of $(document).ready and increment inside the button click. – Neil W Dec 19 '20 at 16:55
1

If i understood correctly then You should remove the random_container and add the textareas below the inputs

<!DOCTYPE html>
<html>
  <head>
    <title>trial </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--bootstrap setup-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="trial.js"></script>

  </head>
<body>
  <div>
    <p> Title</p>
   </div>

   <div>
    <button class = "btn_add">Add  </button>
</div>
<!-- level container-->
<div id = "container">

</div>

</body>

<script>
    function addStaff(btn) {
        var parent = $(btn).parent()
        console.log(parent)
        parent.append(`
            <div id="card">
                <textarea placeholder="Title" type="text" maxlength="10" rows="1">Stuff</textarea>
            </div>
        `)
    }

    $(document).ready(function () {

        var i = 1;
        $(document).on('click', '.btn_add', () => {
            let newElement  = document.createElement('div');
            newElement.setAttribute("id", "level_" + i);
            newElement.setAttribute("class", "panel");
            $('#container').append(`
                <div id="title">
                    Level ${i}
                </div>
                <div id="add_staff-${i}">
                    <button id="btnadd_${i}" onclick="addStaff(this)"> Add Stuff </button>
                </div>
            `);

            $('#container').append(newElement);


            i = i + 1;
        });
    });
</script>

</html>
Kamilg732
  • 13
  • 2
  • 4