Repeat fields according to dropdown number

Asked

Viewed 59 times

1

As I don’t know much about javascript I would like a help of how to do that when choosing a number in the dropdown, I repeated the fields by the chosen value

<select id="valores5" class="valores1 form-control" name="npax">

<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
<option value="6">7</option>
<option value="7">8</option>
<option value="8">9</option>
 </select> 

//loop   x quantidade do select
<div>
<input class="form-control" value="" type="text" name="nome">
<input class="form-control" value="" type="text" name="cpf">
<input class="form-control" value="" type="text" name="tel"> 
<div>
//fim loop
  • I think I got it wrong, you want me to repeat this set (3) of inputs as many times as the value of the option?

  • exact ... repeat the set

  • edited the answer

3 answers

1

You can use Jquery and create according to the ids and classes.

Here’s an example for you to test according to your needs.

$('#valores5').change(function() {
  let valores5 = $('#valores5').val()
  
  $('.div-campo-controle').remove();
  
  for (var i = 0; i < valores5; i++) {
    let novosCampos = $("#campo-modelo").clone()
    novosCampos.attr('id', 'campo='.concat(i + 1));
    novosCampos.addClass('div-campo-controle')
    novosCampos.insertAfter("div.div-campo:last");
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="valores5" class="valores1 form-control" name="npax">

<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
<option value="6">7</option>
<option value="7">8</option>
<option value="8">9</option>
 </select> 

<div id="campos">
<div id="campo-modelo" class="div-campo" >
<input class="form-control" value="" type="text" name="nome">
<input class="form-control" value="" type="text" name="cpf">
<input class="form-control" value="" type="text" name="tel"> 
<div>
<div>

  • Show... that’s right only it’s not removing if we decrease the numbers

  • Just work the logic. You can delete the fields using the remove() method in jquery. https://api.jquery.com/remove/

  • hello friend could not make work remove()

  • and he’s adding up the fields, if you pick 2 and then switch to 3 he shows 5 lines

  • @Fabiohenrique I updated the code as you need. I added a class to the Ivs in the iteration and I remove all the Ivs according to that class before recreating them

1

Pure Javascript

onchange - the event occurs when the value of an element is changed

function criarInputs() {

//recupera o valor do option selecionado (n)
let select = document.getElementById('valores5');
let n = select.options[select.selectedIndex].value;
let campos=""

  for (i = 0; i < n; i++) {
    
   //só pra ver no console.log
   console.log('<input class="form-control" value="" type="text" name="nome"><input class="form-control" value="" type="text" name="cpf"><input class="form-control" value="" type="text" name="tel">');

  } 

}
<select id="valores5" class="valores1 form-control" name="npax" onchange="criarInputs()">

    <option value="0">1</option>
    <option value="1">2</option>
    <option value="2">3</option>
    <option value="3">4</option>
    <option value="4">5</option>
    <option value="5">6</option>
    <option value="6">7</option>
    <option value="7">8</option>
    <option value="8">9</option>

</select>



Note that in the inputs the attribute “name” has the same value for each new set added.

To simplify imagine the following form:

    <form id='form' action="teste.php" method="POST">
        <input type="text" name="nome" value='nome1'>
        <input type="text" name="nome" value='nome2'>
        <button type="submit"> Enviar </button>
    </form>

After making the request, in the.php test I display the information that came from the form and the return is this:

Array ( [nome] => nome2 ) 1

Note that although I have two input’s on the form, only one was sent to me. This is because when a form is submitted and it has several input’s with the attribute value “name” equal, only the latter is considered.

To solve this

So that all input’s with the same attribute value “name” are delivered after request, just add brackets next to the attribute value “name”. Example:

    <input type="text" name="nome[]" value='nome1'>
    <input type="text" name="nome[]" value='nome2'>


Your code would have to be

    function criarInputs() {

      //recupera o valor do option selecionado (n)
    let select = document.getElementById('valores5');
    let n = select.options[select.selectedIndex].value;
    let campos="";

      for (i = 0; i < n; i++) {
           if (n>1){
            console.log('<input class="form-control" value="" type="text" name="nome[]"><input class="form-control" value="" type="text" name="cpf[]"><input class="form-control" value="" type="text" name="tel[]">');
          }else{
            console.log('<input class="form-control" value="" type="text" name="nome"><input class="form-control" value="" type="text" name="cpf"><input class="form-control" value="" type="text" name="tel">');
          }
            
      } 
      document.getElementById("demo").innerHTML = campos;

    }
    <select id="valores5" class="valores1 form-control" name="npax" onchange="criarInputs()">

        <option value="0">1</option>
        <option value="1">2</option>
        <option value="2">3</option>
        <option value="3">4</option>
        <option value="4">5</option>
        <option value="5">6</option>
        <option value="6">7</option>
        <option value="7">8</option>
        <option value="8">9</option>
     </select>
     
     <div id="demo"></div>

For there to be no doubt as to the comment "Quase isso.... só que se eu escolher o numero 4 e depois trocar um menor tipo o 2 ele esta somando 4 mais 2 ao invés de remover"

Let’s run without console.

    function criarInputs() {

      //recupera o valor do option selecionado (n)
    let select = document.getElementById('valores5');
    let n = select.options[select.selectedIndex].value;
    let campos="";

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

          if (n>1){
             campos +='<input class="form-control" value="" type="text" name="nome[]"><input class="form-control" value="" type="text" name="cpf[]"><input class="form-control" value="" type="text" name="tel[]"><br><br>';
          }else{
             campos +='<input class="form-control" value="" type="text" name="nome"><input class="form-control" value="" type="text" name="cpf"><input class="form-control" value="" type="text" name="tel"><br><br>';
          }   
        
      } 
      document.getElementById("demo").innerHTML = campos;

    }
    <select id="valores5" class="valores1 form-control" name="npax" onchange="criarInputs()">

        <option value="0">1</option>
        <option value="1">2</option>
        <option value="2">3</option>
        <option value="3">4</option>
        <option value="4">5</option>
        <option value="5">6</option>
        <option value="6">7</option>
        <option value="7">8</option>
        <option value="8">9</option>
     </select>
     
     <div id="demo"></div>

  • Almost that.... only if I choose number 4 and then change a smaller type o 2 it is adding 4 plus 2 instead of removing

  • @Fabiohenrique take a look at the createFields function of my answer, use that logic there to 'zero' the inputs before inserting them

  • It’s not adding up, it’s that console.log doesn’t erase

  • You can see by the date on the.log console, each selection is a different time

  • @Fabiohenrique, here I see no mistake. Which would be?

  • It may have been before editing that I pasted the wrong code

  • yes that’s right

Show 2 more comments

0

Well, you can generate this html through JS, da para fazer assim:

I set your values in select, there is no pq starting from 0 if you will iterate to generate inputs

<select id="valores5" class="valores1 form-control" onchange='createFields()' name="npax">

<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>
 </select> 
 
 <div id='exemplo'>
 
 </div>

Make a div to be the "wrapper" of your inputs and generate them dynamically. Here’s the script for you to use, I could save a few lines on this code but I left it like this to be a little easier to understand

let parent = document.getElementById('exemplo')

function createDiv () {
  let div_html = document.createElement('div'); // criar uma div pra botar os 3 campos
  //criar os campos com os atributos que você quer
  let input1 = document.createElement('input');
  input1.type = 'text';
  input1.name = 'nome';
  input1.class = 'form-control';
  let input2 = document.createElement('input');
  input2.type = 'text';
  input2.name = 'cpf';
  input2.class = 'form-control';
  let input3 = document.createElement('input');
  input3.type = 'text';
  input3.name = 'tel';
  input3.class = 'form-control';
  // montar a div com os 3 fields
  div_html.appendChild(input1)
  div_html.appendChild(input2)
  div_html.appendChild(input3)
  
  return div_html
}

function createFields() {
  // remover os campos que já estão dentro do parent, pra não ficar adicionando campos um atrás do outro
  while(parent.firstChild) {
    parent.removeChild(parent.firstChild);
}
  let num = document.getElementById('valores5').value // pegar valor do select
  for (let x = 0; x < Number(num); x++) {
   parent.appendChild(createDiv()) // adicionar a div com os fields, iterando o valor do select
  }
 
}

Browser other questions tagged

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