I have a problem adding a new select dynamically in html with javascript, the problem is that I already have a select that loads its content with php and from a database, I have a button so that my users can add a select but the problem is that this select as it is loaded from javascript does not load the data from my database with php, how can I do it?
In the image attached below I have two inputs for people to add a name and a quantity along with an icon to add more fields.
If I click the button to add more fields, they are added correctly:
I want to change the name input for a select that loads its content from my database, if I place the first select with the data loaded from my database, it works without problems but when adding new fields it no longer loads the information.
This is how I load my select:
<label for="sell">Selecciona una empresa:</label>
<select class="form-control" id="empresa" name="empresa">
<?php
$empresas = new ConsultaEmpresa();
$empresasGeneral = $empresas->consultarEmpresas();
foreach ($empresasGeneral as $key => $value) {
echo "<option id='cuenta' value=".$value['id_empresas'].">".$value['empresa']."</option>";
}
?>
</select>
And the way I add my inputs is with JavaScript like this:
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div>'+
'<input type="text" name="field_name[]" placeholder="Agrega un nombre" value=""/> '+
'<input type="text" placeholder="Agrega una cantidad" name="field_cantidad[]" id="cantidad" onKeyPress="return soloNumeros(event)" value=""/>'+
'<a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="img/removeuser.png" width="40px"/></a></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
If the options are the same, you can clone the select, the first thing you do is change the
id
to a class like this:Then to clone it: