How to simplify the code and not repeat so many inputs?

Asked

Viewed 55 times

-3

Hey, guys, come on. I needed to create a + button in a form for the user to click and add, up to a maximum of 10 fields. I could, but I couldn’t get all the data from the form. The database only stored the last form created by the user by clicking the button + .
Faced with the problem I decided to create all the Forms on the page, separate them in Divs and put a select for the user to choose the amount of processes to fill, molds of what would be the + button. The problem is that I had to create many inputs, for example:

Div 1 = 5 inputs Div 2 = 10 inputs Div 3 = 15 inputs . Div 10 = 50 inputs

The code is working, but it took a lot of work because I did this way more crude, after all I do not have much knowledge yet.

Html code (I didn’t put all by size, but it goes up to the div 10)

<div class="Container">
        <form action="#">
            <select name="SelectOptions" id="SelectOptions" required>
                <option value="">Selecione a quantidade de processos</option>
                <option value="Div1">0</option>
                <option value="Div2">1</option>
                <option value="Div3">2</option>
                <option value="Div4">3</option>
                <option value="Div5">4</option>
                <option value="Div6">5</option>
                <option value="Div7">6</option>
                <option value="Div8">7</option>
                <option value="Div9">8</option>
                <option value="Div10">9</option>
                <option value="Div11">10</option>
               
            </select>
        </form>
    
        <div class="DivPai">
            <div class="Div1">
                
            </div>
    <p></p>
            <div class="Div2">
                <input type="text" name="nomecac"  placeholder= "Nome do CAC">
                <input type="text" name="cpfcac"  placeholder= "CPF do CAC">
                <input type="text" name="numerosigma" placeholder= "Numero do Sigma">
                <select name="tipo" type="text" >
                    <option value="" disabled selected >Qual documento deseja retirar?</option>
                    <option value="Guia de Trafego">Guia de tráfego</option>
                    <option value="craf">Retirar Craf</option>
                </select>
                <input type="text" name="numerodoc" placeholder= "Quantidade de documentos à retirar">
            </div>
    
            <div class="Div3">
                <input type="text" name="nomecac1"  placeholder= "Nome do CAC">
                <input type="text" name="cpfcac1"  placeholder= "CPF do CAC">
                <input type="text" name="numerosigma1" placeholder= "Numero do Sigma">
                <select name="tipo1" type="text" >
                    <option value="" disabled selected >Qual documento deseja retirar?</option>
                    <option value="Guia de trafego">Guia de tráfego</option>
                    <option value="craf">Retirar Craf</option>
                </select>
                <input type="text" name="numerodoc1" placeholder= "Quantidade de documentos à retirar">
                <p></p>
                <input type="text" name="nomecac2"  placeholder= "Nome do CAC">
                <input type="text" name="cpfcac2"  placeholder= "CPF do CAC">
                <input type="text" name="numerosigma2" placeholder= "Numero do Sigma">
                <select name="tipo2" type="text" >
                    <option value="" disabled selected >Qual documento deseja retirar?</option>
                    <option value="guia de trafego">Guia de tráfego</option>
                    <option value="craf">Retirar Craf</option>
                </select>
                <input type="text" name="numerodoc2" placeholder= "Quantidade de documentos à retirar">
            </div>


With each div above in the code, I added 5 more inputs for when the user selects the amount of processes, show exactly the number he requested.

Hide fields with Jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>//Funções após a leitura do documento
$(document).ready(function() {
    //Select para mostrar e esconder divs
    $('#SelectOptions').on('change',function(){
        var SelectValue='.'+$(this).val();
        $('.DivPai div').hide();
        $(SelectValue).toggle();
    });
});</script>

CSS

<style type="text/css">
    .Div1,.Div2,.Div3,.Div4,.Div5,.Div6,.Div7,.Div8,.Div9,.Div10,.Div11 {display:none;}
  </style>

PHP that receives write to database (added the variables in relation to the third div as well)

<?php 
// RECEBENDO OS DADOS PREENCHIDOS DO FORMULÁRIO !
$tipo   = $_POST ["tipo"];
$nomecac    = $_POST ["nomecac"];   
$cpfcac = $_POST ["cpfcac"];    
$numerodoc  = $_POST ["numerodoc"];  
$numerosigma    = $_POST ["numerosigma"];   
$tipo1  = $_POST ["tipo1"];
$nomecac1   = $_POST ["nomecac1"];  
$cpfcac1    = $_POST ["cpfcac1"];   
$numerodoc1 = $_POST ["numerodoc1"];     
$numerosigma1   = $_POST ["numerosigma1"];  
$tipo2  = $_POST ["tipo2"];
$nomecac2   = $_POST ["nomecac2"];  
$cpfcac2    = $_POST ["cpfcac2"];   
$numerodoc2 = $_POST ["numerodoc2"];     
$numerosigma2   = $_POST ["numerosigma2"];  
$tipo3  = $_POST ["tipo3"];
$nomecac3   = $_POST ["nomecac3"];  
$cpfcac3    = $_POST ["cpfcac3"];   
$numerodoc3 = $_POST ["numerodoc3"];     
$numerosigma3   = $_POST ["numerosigma3"];

//Gravando no banco de dados !

$mysqli = mysqli_connect("servidor", "...", "....", ".....");

$squery = "INSERT INTO agenda (tipo, nome, cpf, doc, numerosig) VALUES ('$tipo, $tipo1, $tipo2, $tipo3 ','$nomecac, $nomecac1, $nomecac2, $nomecac3','$cpfcac, $cpfcac1, $cpfcac2, $cpfcac3','$numerodoc,$numerodoc1, $numerodoc2, $numerodoc3','$numerosigma, $numerosigma1, $numerosigma2, $numerosigma3')

$resultado = mysqli_query($mysqli,$squery);

I put the shorthand codes so I don’t get giant here.

By way of learning, what would be a good way to simplify my code and not have to create so many inputs? Sorry for any ignorance in the code, I hope to laugh at it in a few years hahah.

  • 2

    Please edit the question to limit it to a specific problem with sufficient detail to identify an appropriate answer.

  • A tip: use the name of the inputs in the form of an array, thus: name="nomecac[]"... the brackets mean that you can send multiple fields with the same name array-like.

  • Yes, I did it initially, but in the database it appeared only written 'array' and not the values

1 answer

-1

You can create fields dynamically using strings template. Just take the selected amount from select and make a loop with the chosen amount and add the HTML to the parent div. We already have name form fields you add brackets [] to be sent as an array to PHP.

$(function(){
   
   $("#SelectOptions").on("change", function(){
      
      var qtd = $(this).val();
      
      if(qtd){
         
         var html = '';
         
         for(var x = 1; x <= qtd; x++){
         
            html += `<div class="divFilho"><p>${ x }</p>
            <input type="text" name="nomecac[]"  placeholder= "Nome do CAC">
            <input type="text" name="cpfcac[]"  placeholder= "CPF do CAC">
            <input type="text" name="numerosigma[]" placeholder= "Numero do Sigma">
            <select name="tipo[]" type="text" >
               <option value="" disabled selected>Qual documento deseja retirar?</option>
               <option value="Guia de Trafego">Guia de tráfego</option>
               <option value="craf">Retirar Craf</option>
            </select>
            <input type="text" name="numerodoc[]" placeholder= "Quantidade de documentos à retirar"></div>`;

         }
         
         $(".DivPai").html(html);
         
      }else{

         $(".DivPai").empty();

      }
      
   });
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="SelectOptions" id="SelectOptions" required>
   <option value="">Selecione a quantidade de processos</option>
   <option value="0">0</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
   <option value="5">5</option>
   <option value="6">6</option>
   <option value="7">7</option>
   <option value="8">8</option>
   <option value="9">9</option>
   <option value="10">10</option>
</select>
<div class="DivPai">
</div>

In PHP you will receive the fields normally with $_POST, for example:

$tipo = $_POST["tipo"];

The variable $tipo, for example, it will be an array, where you must make a loop to traverse each item of that array, which are the values of the fields sent with the name="tipo[]".

An example to go through the entire array would be with for:

for($x = 0; $x < sizeof($tipo); $x++){
   echo $tipo[$x];
}

Browser other questions tagged

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