Home > OS >  jQuery click event then create multiple group of divs
jQuery click event then create multiple group of divs

Time:06-20

I have jQuery click event which is create group of div or container for every clicking the button . All I want is to create a container every click on a button.

Here is the HTML container create on every button click.

<button type="button" id="add_container">Add Container</button

<div >
 <div >
  <span>I'm the Label</span>
 </div>
 <div >
  <div >
   <select container">...</div>
})

CodePudding user response:

First Create a dummy div as shown below -

HTML -

<button type="button" id="add_container">Add Container</button

<div ></div>

JQuery -

$('#add_container').on('click', function(){
   var html = '<div ><div ><span>I'm the Label</span></div><div ><div ><select snippet-code-js lang-js prettyprint-override">$('#add_container').on('click', function() {
  $(".container:first").clone().insertAfter("div.container:last")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="add_container">Add Container</button

<div >
  <div >
    <div >
      <span>I'm the Label</span>
    </div>
    <div >
      <div >
    <select >
    <option>Choose 1</option>
    <option>Choose 2</option>
   </select>
  </div>
 </div>
</div>
</div>

CodePudding user response:

You can add a container wrapper and append a child to it:

HTML:

<button type="button" id="add_container">Add Container</button>

<div >
    <div >
        <div >
            <span>I'm the Label</span>
        </div>
        <div >
            <div >
                <select >
                    <option>Choose 1</option>
                    <option>Choose 2</option>
                </select>
            </div>
        </div>
    </div>
</div>

jQuery:

$('#add_container').on('click', function(){

    console.log('Clicked!', 'add_container');

    $('.wrapper').append(
        '<div >'
          '<div >'
              '<span>I\'m the Label</span>'
          '</div>'
          '<div >'
              '<div >'
                  '<select >'
                      '<option>Choose 1</option>'
                      '<option>Choose 2</option>'
                  '</select>'
              '</div>'
          '</div>'
      '</div>');
})
  • Related