remove dynamic div with jQuery counter

2

Hi,

I'm generating fields dynamically using Jquery, and for each field I add at the end of the id a counter. I was wondering how I could do to remove the div that encompasses the button and the fields.

this is my form:

$contador = '';
foreach ($programas as $key => $formu){ $contador += 1;?>
<div id="campos_<?php echo $contador; ?>" name="campos[]" class="campos col-md-12" >
   <input id="tbprogramacao_tv_hora_inicio_<?php echo $contador; ?>" class="form-control hora" type="text" value="<?php echo $formu->getHoraInicio(); ?>" name="tbprogramacao_tv[hora_inicio][]" maxlength="8">
    <br><div class='btn btn-primary' style="border:solid 1px;" id="rmv" onclick="remover()"><span class="fa fa-minus"></span></div>
 </div>

This is the function I'm creating to remove:

function remover()
{
    $('.campos').remove();
}

but does not work. Anyone who has been through this can help me?

    
asked by anonymous 28.10.2015 / 20:17

3 answers

3

In onclick, pass the id of the field as a parameter:

onclick="remover('campos_<?php echo $contador; ?>')"

and in the remove function use remove() in the field id:

function remover(campo)
{
    $('#'+campo).remove();
}
    
28.10.2015 / 20:27
0

As every field is inside a div, you can pass the button element ( this ) to the function and remove the div that is the parent ( parent ).

function remover(elemento) {
  $(elemento).parent().remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><divid="campos_1" name="campos[]" class="campos col-md-12">
  <input id="tbprogramacao_tv_hora_inicio_1" class="form-control hora" type="text" value="1" name="tbprogramacao_tv[hora_inicio][]" maxlength="8">

  <input type="button" onclick="remover(this);" class="btn btn-primary" value="Remover">
  </span>
</div>
</div>
<Br>
<div id="campos_1" name="campos[]" class="campos col-md-12">
  <input id="tbprogramacao_tv_hora_inicio_2" class="form-control hora" type="text" value="2" name="tbprogramacao_tv[hora_inicio][]" maxlength="8">
  <input type="button" onclick="remover(this);" class="btn btn-primary" value="Remover">
  </span>
</div>
</div>
    
28.10.2015 / 20:41
0

Try this:

$("#rmv").click(function{
      $('.campos').remove();
});

Make sure that the div you want to remove has a class called fields.

See working at: Jsfiddle

    
28.10.2015 / 20:25