remove dynamic div with jQuery counter

Asked

Viewed 283 times

2

Hi,

I am generating fields dynamically using Jquery, and for each field I add at the end of id a counter. I wondered 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 am creating to remove:

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

but it doesn’t work. Someone who’s been through it can help me?

  • When you use "." you are referring to the class. For id use "#", for tag (div, label, etc.) use only the name. In the jQuery documentation you have a list of all https://api.jquery.com/category/selectors/

3 answers

3


in onclick pass the id of the field as parameter:

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

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

function remover(campo)
{
    $('#'+campo).remove();
}

0

Try it like this:

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

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

See working on: Jsfiddle

0

As every field is inside a div, you can pass the button element (this) in the function and remove the div who 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>

<div id="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>

Browser other questions tagged

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