How to add and remove selects with jquery?

0

Hi, I have a jquery code that works perfectly for me to add new inputs. The problem is that I also need to add dynamic selects for my system and I really do not understand the syntax of jquery. I would greatly appreciate your help. Certainly the select makes a query to the database.

 // Añadir caja de texto.
    $(container).append('<input type=text required="required" name ="fields[]" class="input" id=tb' + iCnt + ' ' +
    'placeholder="Producto ' + iCnt + '" />');
     <select name="producto">
     <?php

                        $sql = "Select producto from productos";

        $query = $db->prepare($sql);
        $query->execute();
           while($row = $query->fetch(PDO::FETCH_ASSOC)) {
        echo '<option>'.$row['producto'].'</option>';
           }
         ?>
     </select>
    
asked by Daniel Treviño 01.09.2017 в 17:04
source

1 answer

1

If you want to add controls select with jquery, you can create the element select in memory, then create each option to select and then add the select to the element where you want it to appear.

Here is an example:

$("button").click(function(){
 
  var select = $(document.createElement("select"));
  
  // agregamos las opciones al select
  var options = ["Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"];
  for(var i = 0; i < options.length; i++)
  {
    var option = $(document.createElement("option"));
    option.val(options[i]);
    option.text(options[i]);
    
    //agregamos el option al select
    select.append(option);
  }
  
  // agregamos el select al documento
  $("body").append(select);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Crear select</button>
    
answered by 01.09.2017 в 17:11