I'm creating a Dynamically Add/Remove input fields for my project. One of the column has a select type of input and the options needs to be from a table in database. It is working perfectly on the first row but when I needed to add more fields, it doesn't work. Is it possible to put php codes on .append function in jquery?
I tried doing the same process on the first row for .append function, but when I add more fields, it doesn't add anything. When I removed the php codes, it is working, but not with the options from database. I don't know if I have syntax error in displaying the values from database in append function.
<?php
<tr>
<td>
<select class="form-control" name="procedures[]">
<?php
$sql = "SELECT * FROM services";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
echo '<option>'.$row['s_name'].'</option>
';
}
?>
</select>
</td>
<td><input type="text" name="description[]" placeholder="Description" class="form-control name_list" /></td>
<td><input type="text" name="amount[]" placeholder="Amount" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">+</button></td>
</tr>
This is the append function that add more text fields just like the format of row above.
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><select class="form-control" name="procedures[]"><?php $sql="SELECT * FROM services"; $result=mysqli_query($conn,$sql); while($row=mysqli_fetch_array($result)){ echo "<option>'".$row['s_name']."'</option>";}?></select> </td><td><input type="text" name="description[]" placeholder="Description" class="form-control name_list" /></td><td><input type="text" name="amount[]" placeholder="Amount" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">x</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
I expect that I can add more input fields as same with the first row which has a column of select input with options from a table in database. Click here to see the image