Jquery . after()

Asked

Viewed 111 times

1

The error in the code is that when I click on the "Add" button new input file, the intention is to add only one field after the last one, but the button triples.

My HTML code looks like this:

<div class="col-md-8">
  <div class="form-group input-files">
    <input type="file" name="imagem_file[]" class="form-control">
  </div>
  <div class="form-group input-files">
    <input type="file" name="imagem_file[]" class="form-control">
  </div>
  <div class="form-group input-files">
    <input type="file" name="imagem_file[]" class="form-control">
  </div>
</div>

And the button for action:

<button onClick="addInput();" class="btn btn-sm btn-info">[+]</button>

Javascript looks like this:

<script>
function addInput(){
    $(".input-files").after('<div class="form-group input-files"><input type="file" name="imagem_file[]" class="form-control"></div>');
}
</script>

If you leave only one input file field, it generates another, but from there it multiplies by the amount that is being generated.

The example in Codepen.io.

1 answer

2


The selector ".input-files" hits 3 <div class="input-files"> of its original html, for this reason it adds a new element after each one. Instead you can only catch the last one by adding to the selector :last

function addInput(){
    $(".input-files:last").after('<div class="form-group input-files"><input type="file" name="imagem_file[]" class="form-control"></div>');
    //----------------^ aqui
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-8">
  <div class="form-group input-files">
    <input type="file" name="imagem_file[]" class="form-control">
  </div>
  <div class="form-group input-files">
    <input type="file" name="imagem_file[]" class="form-control">
  </div>
  <div class="form-group input-files">
    <input type="file" name="imagem_file[]" class="form-control">
  </div>
</div>

<button onClick="addInput();" class="btn btn-sm btn-info">[+]</button>

Confirm this dial on jquery selector reference.

Alternatively you could have used the selector :last-child css, that would still work.

  • Thank you, that’s right, it worked! in 9min I accept the answer by default here, and to remove I do the same? I use :last with the . remove(); right?

  • 1

    @Eliseub. Yes, if you want to remove the last .input-files that exists

  • I had it removed and it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.