How to generate multiple inputs within a repeat loop

Asked

Viewed 607 times

1

I need to create inputs based on the amount the user types.

For example:

var quantidade = 5; \\\usuario digitou

for(int i = 0; i< quantidade; i++){
   //aqui vem os inputs
}

In that case I would also need to change the name of each input and then send by the method POST to place in a database.

That’s the logic I found, I’m open to others. Follow the statement of the problem:

  1. Class name and number of students insertion page

  2. Page containing an HTML form with the fields:

    • Student’s name
    • Note 1
    • Note 2
    • Note 3
  • https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta

3 answers

2


The Names will be A0, A1, A2 etc.....

    
var quantidade = 5;

for(i = 0; i< quantidade; i++){

   var x=document.getElementById('myTable').insertRow(0);
   
    var y=x.insertCell(0);
    
    y.innerHTML="<input type=text name=A" + i + ">";
}
<form action="pagina_destino" method="post">
<table id="myTable" border="0">
    <tr>
    <td></td>
    </tr>
</table>
</form>

insertRow - inserts a new line

insertCell - inserts a <td> with some content in it.

With javascript and inside div

    var quantidade = 5;
    var conteudo="";
    for(i = 0; i< quantidade; i++){
        conteudo +=('<input type="text" name="A'+i+'"/>');
    };

    document.getElementById("demo").innerHTML=conteudo;
<form action="" method="post">
    <div id="demo"></div>
    <input type="submit">
</form>

With jquery

var quantidade = 5;
var conteudo="";
    	
for(i = 0; i< quantidade; i++){
    	    
    conteudo +='<input type="text" name="A'+i+'"/><br>';
    	         
};
    	     
$('.container').append(conteudo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
   <div class="container"></div>
   <input type="submit">
</form>

  • Your solution is great and helped me, but you could create these inputs in the same way with a <div> instead of a table?

  • Thank you! You helped me a lot!

1

Look, I don’t think my answer will completely solve your problem because I’m not very advanced with js, but I can give you an idea of how to do it for the knowledge I have:

The first image is the code and the second is the result in html.

In js I am first getting the value typed by the user in the loop I am selecting the div that I will add the inputs that in this case is the one with id "inputs". After that I am creating an input element and adding the attributes name and id in them. Then I give an append to the div causing the inputs to be added to the html.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

<form action="pagina_destino" method="post">
<div id="mydiv">

</div>
</form>


var quantidade = 3
for(i = 0; i< quantidade; i++){

var x=document.getElementById('mydiv')

var y = document.createElement("input")
y.setAttribute("name", `input${i}`)
y.setAttribute("type", "text")

x.appendChild(y)
}
  • Your solution is good and works. I had a vision of how to do it, but I’m not able to perform the function without creating a button. In my case, the function needs to be executed automatically. When the user enters the page, the inputs already have to be created. That is, it will type the quantity on one page and then be redirected to another, with the inputs created.

  • I tried to answer your question about the comment down there, take a look and see if it helps you.

  • Thank you! You helped me a lot!

0

I ended up using PHP same, but the two answers helped me a lot in another part of the program in which I need to necessarily build by Javascript, thank you very much!.

Follow the solution code snippet:

<form class="needs-validation" novalidate name="frmCadastroDeTurma" method="POST" action="inserirNotas.php">
      <?php
            $j = 0; $a = 1;
            for ($i = 0; $i < $_SESSION['qtdAlunos']; $i++){
        ?>
        <div class="row">

          <div class="col-md-6 mb-3">
            <label for="Nome da Turma">Nome do Aluno</label>
            <input type="text" class="form-control"  placeholder="" value="" required name="<?php echo "nomeAluno" . $i; ?>">
            <div class="invalid-feedback">
               Nome do Aluno é requirido.
            </div>
            <label class="tituloAluno" ><?php echo "ALUNO    " . $a++;?></label>

          </div>
          <div class="col-md-6 mb-5">
            <label for="Primeira Nota">Primeira Nota</label>
            <input type="text" class="form-control" onkeyup="somenteNumeros(this);"  placeholder="" value="" required name="<?php echo "primeiraNota" . $j++; ?>">
            <div class="invalid-feedback">
               Primeira nota é requirida.
            </div>
            <hr class="hrInputs" >
            <label for="Segunda Nota">Segunda Nota</label>
            <input type="text" class="form-control" onkeyup="somenteNumeros(this);"  placeholder="" value="" required name="<?php echo "segundaNota" . $j++; ?>">
            <div class="invalid-feedback">
               Segunda Nota é requirida.
            </div>
            <hr class="hrInputs">
            <label for="Terceira Nota">Terceira Nota</label>
            <input type="text" class="form-control" onkeyup="somenteNumeros(this);"  placeholder="" value="" required name="<?php echo "terceiraNota" . $j++; ?>">
            <div class="invalid-feedback">
               Terceira nota é requirida.
            </div>
            <hr class="hrInputs">
          </div>

        </div>
        <hr class="hrDivisor">
        <?php 
            }
        ?>


        <button class="btn btn-primary btn-lg btn-block" type="submit">Salvar</button>

      </form>

I used Bootstrap and Jquery for styling.

  • Fine, just a hint, in the next questions, if you want to accept answers with other languages/technologies, include the corresponding tags in the question to signal that you accept answers with the same!

  • Your code will generate multiple elements (hrs, Labels) with same id. I believe it won’t make a difference but it’s not in the constitution!!!

  • I had put the PHP tag but the question was edited by someone else.

  • About the ids, I managed to change the "placeholder" to class, but the other ids repeat themselves because I haven’t yet touched the Boostrap css to change the classes.

  • But thanks for remembering! It was something I had already forgotten.

  • I’ll edit the code here and put it right.

Show 1 more comment

Browser other questions tagged

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