Add one more ID when generating one more INPUT via javascript

Asked

Viewed 66 times

2

I’m creating a voting system, and before the person generates the input with the options, the person has to choose the number of options they will have, then they go to a form with the alternatives according to the amount they have chosen, but I want to put something like Add one more field, and I got through JAVASCRIPT.

Only that he is not able to count the fields coming through javascript:

Through javascript it puts one more field when one clicks on the Button, after the idDiv div...

        
        echo'<form action="valida_enquete.php" method="POST" accept-charset="utf-8">
            Título da sua enquete:<input type="text" name="titulo_enquete"><br>
            Descrição da enquete: <input type="text" name="descricao_enquete"><br><br>';
            
            if(isset($_GET['qtdade_opcoes'])){
                
                ?>
                <div id="idDiv">
                <?php
                for ($i=0; $i<$_GET['qtdade_opcoes']; $i++) { 
                    
                    $indice = $i+1;
                    echo'opção <input type="text" name="opcao[]"><br>';
                    echo'imagem <input type="text" name="img[]"><br>';
                

                echo' <input type="hidden" name="numero" value="'.$_GET['qtdade_opcoes'].'">';
                }
                echo '
                
                <input type="hidden" name="reality" value="'.$row['reality'].'">
                
                </div>';
            }
        
    ?>  

Javascript code

window.onload = function () {
$(document).ready(function() {
   var maximo = 5;   //maximo de 5 campos
   var i = 1;
   $('#add_div').click (function(e) {
     e.preventDefault();  //previne novos cliques
     if (i < maximo) {
       $('#idDiv').append('<div>\
          opção: <input type="text" name="opcao[]"/> <br> imagem:  <input type="text" name="img[]"/>\
          <a href="#" class="remove">Remover</a>\
           <?php    echo' <input type="hidden" name="numero" value="'.$_GET['qtdade_opcoes'].'">';
           ?></div>');
           i++;
     }
  });
 
    // Remove o div anterior
    $('#idDiv').on("click",".remove",function(e) {
      e.preventDefault();
      $(this).parent('div').remove();
      i--;
    });
});
};

Somebody help me, please?

1 answer

2


No need to declare this variable i = 1 and then incrementing, you can get this value always updated in the click using for example this selector: var i = $("#idDiv > div").length; i.e., the Ivs nested within div with id "idDiv", and length to return the amount.

Simply put, it would look like this (includes some comments):

window.onload = function () {
$(document).ready(function() {
   var maximo = 5;   //maximo de 5 campos
  
   $('#add_div').click (function(e) {
     e.preventDefault();  //previne novos cliques

      // total de divs aninhados abaixo de idDiv
      var i = $("#idDiv > div").length;

     // inverti esse if, para não ficar todo o código aninhado, e sair logo se puder adicionar nos itens
     if (i >= maximo) return;
     
     $('#idDiv').append('<div>\
opção: <input type="text" name="opcao[]"/> <br> imagem:  <input type="text" name="img[]"/>\
<a href="#" class="remove">Remover</a></div>');

  });
 
    // Remove o div anterior
    $('#idDiv').on("click",".remove",function(e) {
      e.preventDefault();
      $(this).parent('div').remove();
    });
});
};
#idDiv > div {
   padding: 5px;
   border: solid 1px #ddd;
   background-color: #eee
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="idDiv">
  <div>
    opção: <input type="text" name="opcao[]"><br>
    imagem: <input type="text" name="img[]"><br>  
  </div>
</div>

<button id="add_div">Adicionar</button>

  • But I need the amount of inputs to be within that input, which goes along with $_GET['qty_options'] whenever one adds one more input and so on... <input type="Hidden" name="number" value="'. $_GET['qty_options'].'">

  • you can therefore in the code, I removed pq would not work in the example, this ai is PHP, but it does not change the fact that, if you are adding/removing elements with javascript, does it on the client side, and either use that variable or always take the amount of elements using a selector

  • I put it and it doesn’t take the amount of items that javascript adds, how do I get this amount? this is the question

  • var i = $("#idDiv > div").length; this variable has the amount of "items" (Divs). In your code, you have a Hidden input with the amount of opiations, just take the value of this input and subtract the amount of items you have if I understand correctly. It may be so: var totOpicoes =$('input[name ="numero"]').val()

  • I swear it’s the last time, and how do I get in PHP a javascript tag?

  • pq this value has to be inside the input for me to add

  • you may ask, if you do POST page, can do so: $_REQUEST['numero']. Now if you want the total of fields, I suggest creating another Hidden field to store that value, for example <input t ype="hidden" name="totalItens" />. In this case, it uses the same command, only the name of that other input. Now in javascript you need to update it each time you add or remove an item. For example, when adding an item, after doing the append, updates this field: $('input[name ="totalItens"]').val(i+1), "i" is the variable that has the total of items, as adicinou plus one, just add 1

  • DEUUUUUU CERTO MTO THANKS!

  • Ricardoooo, just one more thing, when you have removing the field it has to take -1 back, I put $('input[name ="totalItens"]'). val(i-1) after removing it, only it is giving error

  • You copied the code var i = $("#idDiv > div").length; into the Function that makes delete? can be this

  • Thank you very much, another thing, I’m trying to show you the option number with the following code ' + $("#idDiv > #Alternativadiv"). length' however it is showing from 0, how do I start from 2?

Show 6 more comments

Browser other questions tagged

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