Change the value of a parameter passed to a function

2

I have a dynamic form that I add several fields and I create together a div that is passed by a button that is assigned a onClick event for it passing a function that receives a parameter. This parameter is a sequential number that I create through a foreach with an array of the DB. But when I click on adding another field, this parameter of the function remains the same, not incrementing. I wanted to be able to increment the value of the parameter, but I do not know how to do this via Jquey.

<?php 
 $contador = '';
 foreach ($programas as $key => $formu)
 {
   $contador += 1;
 ?>
<div id="campos_<?php echo $contador; ?>" name="campos[]" class="campos col-md-12" >
<br><div class="btn btn-primary"  id="rmv_<?php echo $contador; ?>"   onclick="remover('campos_<?php echo $contador; ?>')"><span class="fa fa-minus"></span></div>
</div>

Notice that I want to increment this:

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

I can increment the id counters through jquery like this:

campos.children().find("#rmv_"+(contador)).attr('id','rmv_'+(comentario+1));

but I have no idea how to change this parameter value.

Can anyone who has gone through this help me?

    
asked by anonymous 29.10.2015 / 18:49

2 answers

1

You can use a hidden field to save the value of your counter, manipulate with javascript and send to the backend with ajax or in the post.

<?php 
  $contador = '';
  foreach ($programas as $key => $formu)
  {
      $contador += 1;
  }
?>

<input id="contador" name="contador" type="hidden" value="<?php echo $contador; ?>" />

<div id="campos_<?php echo $contador; ?>" name="campos[]" class="campos col-md-12" >
    <br><div class="btn btn-primary"  id="rmv_<?php echo $contador; ?>"   onclick="remover('campos_<?php echo $contador; ?>')"><span class="fa fa-minus"></span></div>
</div>

Javascript:

function criarCampo() {
     var contador = $('#contador').val();

     //incrementa o contador
     +contador++;

     //TODO: Cria o campo com o contador incrementado "campos_"+contador

     //Atualiza o contador no campo hidden

     $('#contador').val(contador);
}
    
29.10.2015 / 20:22
1

If you simply need to get the id (counter) of each element in the remover() function, you can do this:

<br><div class="btn btn-primary"  id="rmv_<?php echo $contador; ?>"   onclick="remover(this)" data-contador="<?php echo $contador; ?>"><span class="fa fa-minus"></span></div>

And in the remover() function:

function remover() {
   var contador = $(this).data('contador');

   //faça o que tiver que fazer com o contador
}
    
29.10.2015 / 22:19