Adam
Adam

Reputation: 507

Clone just one field and append once per click

I have an input to upload a new file, also I have a button to add another file without page reloading to upload multiple files at once. When I click Add another file for the first time it's adding the new field as expected so in totall I have two fields, The problem occurs after another click I get 4fields than 8 etc. I want to add only one field per click. Code:

<script type="text/javascript">
    $("#file-new").click(function () {
        $( ".file-item" ).clone(false).appendTo( "#files-container" );
    });
</script>

And as always thank you for help! :)

Upvotes: 0

Views: 291

Answers (2)

sphinxplayer
sphinxplayer

Reputation: 330

Using jQuery :

function initiateFiles ()
{
  let 
    $fileNew = $( '#file-new' ),
    $container = $( '#files-container' ),
    $item = $( '<div>', { class: 'file-item' } );    
  
  $fileNew.click( () => {
    
    $item.clone().appendTo( $container );
    
  });
}

initiateFiles();
#files-container
{
  width: 200px;
  height: auto;
  padding: 10px;
  border: 1px dashed #000;
}

.file-item
{
  width: 90%;
  height: 10px;
  border: 1px solid #000;
  margin: 5px auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="file-new">New File</button>
<div id="files-container"></div>

Upvotes: 1

full-stack
full-stack

Reputation: 553

Clone only the first element with the fileItem class

 $("#file-new").click(function () {
        $( ".file-item:first" ).clone(false).appendTo( "#files-container" );
    });

Upvotes: 2

Related Questions