This is a script that I use to add a set of form fields on clicking an Add More button:
<script>
$(document).ready(function() {
var InputsWrapper = $("#InputsWrapper");
var AddButton = $("#AddMoreFileBox");
var x = InputsWrapper.length;
var FieldCount = 1;
$(AddButton).click(function(e)//on add input button click
{
FieldCount++;
$(InputsWrapper).append('<tr><td><input id="find" type="text" name="item[]"></td><td><input id="find" type="number" name="qty[]"></td><td><input id="find" type="number" name="price[]"></td><td><input id="find" type="number" name="discount[]"></td><td> <?php $query = mysqli_query($con, "SELECT * FROM `tax_vat` "); echo '<select name="vat" id="find" data-required="true"><option value="">Select Vat</option>"';while ($row = mysqli_fetch_array($query)) {echo '<option value="' . $row['vat_rate'] . '">' . $row['vat_description'] . '</option></br>';}echo '</select>';?></td><td><input id="find" type="number" name="total[]" readonly ></td></tr>');
x++;
return false;
});
});
</script>
This is the form:
<table id="InputsWrapper" >
<tr>
<span class="small"><a href="#" id="AddMoreFileBox" class="btn btn-info">Add More Field</a></span>
</tr>
<tr>
<td><label for='item'>Item:</label></td><td><label for='qty'>Quantity:</label></td><td><label for='price'>Price:</label></td><td><label for='discount'>Discount %</label></td><td><label for='vat'>VAT %:</label></td><td><label for='total'>Final Price:</label></td>
</tr>
<tr>
<td><input class='item form-control' id="find" type='text' name='item[]' required></td>
<td><input class='qty form-control' id="find" type='number' name='qty[]' required></td>
<td><input class='price form-control' id="find" type='number' name='price[]' required></td>
<td><input class='discount form-control' id="find" type='number' name='discount[]' required></td>
<td><?php $query = mysqli_query($con, "SELECT * FROM `tax_vat` "); echo '<select name="vat" id="find" data-required="true"><option value="">Select Vat</option>"';while ($row = mysqli_fetch_array($query)) {echo '<option value="' . $row['vat_rate'] . '">' . $row['vat_description'] . '</option></br>';}echo '</select>';?></td>
<td><input class='total form-control' id="find" type='number' name='total[]' readonly required></td>
</tr>
</table>
Total : <input id='totaldp' class="form-control" type='number' name='totaldp' readonly required>
<input type="hidden" id="name_id" name="name_id" />
In the form, there is a dropdown box which fetch certain details from the database. The PHP code to fetch and display the dropdown box is coded in the form so that it is displayed on the initial load of the page, and then, the same code is coded in the append
function the script so that the same set of input fields are displayed on clicking the Add More button.
The whole thing works perfectly fine. But the code looks terribly ugly. Is there a better way to do it?