Jquery .after ()

1

The error in the code is that when I click the "Add" new input file button, the intention is to add only one field after the last, 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 the action:

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

The 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 being generated.

The example in Codepen.io .

    
asked by anonymous 10.03.2018 / 17:16

1 answer

2

The ".input-files" selector hits 3% with% of your original html, so add a new element next to each one. Instead you can just pick the last one by adding to the <div class="input-files">

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><divclass="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 selector in the JQuery selector reference .

Alternatively, you could have used the % s of CSS selector, which would work in it.

    
10.03.2018 / 17:21