Insert from dynamic table input to mySQL - javascript

I have a dynamic table form input form which you can add/remove rows as you like. As someone who doesn't have much experience, I'm stuck on how to save those input into the mySQL database.
Here's what the input.php looks like
<form action="insert.php" method="post">
<div class="box-body no-padding">
<table class="table table-bordered">
<tr>
<th>Item</th>
<th>#</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
<tr>
<td><input type="text" id="item" name="item"></td>
<td><input type="text" id="no" name="no"disabled></td>
<td><input type="number" id="qty" name="qty"></td>
<td><input type="number" id="price" name="price"></td>
<td><input type="number" id="total" name ="total" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
</table>
</div>
<div class="box-body">
<div class="button-group">
<i class="fa fa-plus-circle"></i> Add Item
</div>
</div>
<div class="box-footer">
<div class="button-group pull-right">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
And here is the JS (jQuery) code that I use to add/remove rows
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function(){
$(document).ready(function(){
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item'></td>";
var no = "<td><input type='text' id='no' disabled></td>";
var qty = "<td><input type='number' id='qty'></td>";
var price = "<td><input type='number' id='price'></td>";
var total = "<td><input type='number' id='total' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
$(".table").on('click', '.remove-row', function(){
$(this).closest("tr").remove();
});
});
});
</script>
Here's what the page looks like:
input page
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db", $connection);
if(isset($_POST['submit'])){
$item = $_POST['item'];
$no = $_POST['no'];
$qty = $_POST['qty'];
$price = $_POST['price'];
$query = mysql_query("insert into table(item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
?>
I know the insert.php won't work for my case because I need to input it as arrays. The thing is:
1. I don't know how to implement the front end so I won't have duplicate id/names when I click "Add Item"
2. I don't know how to insert the arrays (that I don't know to create) to the mysql.
I'd like to know how can I implement the save button in my case. Thank's for your help.

First, please research the mysql_* functions. They should no longer be used because they can lead to SQL injection security issues. Use mysqli_* instead or a DB layer like PDO.
Second, if you append "[]" to your input tag names then PHP will receive the data as arrays and you can loop through it in your insert.php.
<tr>
<td><input type="text" id="item" name="item[]"></td>
<td><input type="text" id="no" name="no[]" disabled></td>
<td><input type="number" id="qty" name="qty[]"></td>
<td><input type="number" id="price" name="price[]"></td>
<td><input type="number" id="total" name="total[]" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
And be sure your javascript code also adds the name attribute:
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item' name='item[]'></td>";
var no = "<td><input type='text' id='no' name='no[]' disabled></td>";
var qty = "<td><input type='number' id='qty' name='qty[]'></td>";
var price = "<td><input type='number' id='price' name='price[]'></td>";
var total = "<td><input type='number' id='total' name='total[]' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
Then in PHP you can have:
<?php
$connection = mysqli_connect("localhost", "root", "", "db");
if(isset($_POST['submit'])){
$rowCount = count($_POST['item']);
// Note that this assumes all the variables will correctly be submitted as arrays of the same length. For completeness and robustness you could add a !empty check for each value.
for ($i = 0; $i < $rowCount; $i++) {
$item = $_POST['item'][$i];
$no = $_POST['no'][$i];
$qty = $_POST['qty'][$i];
$price = $_POST['price'][$i];
$query = mysqli_query($connection, "insert into `table` (item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
}
?>

Related

how to hide table row by applying filter variables using javascript?

FYI- I am making a timesheet project using PHP and MySQL
I am new to PHP, I tried to use PHP make HTML table rows and assign them row id, but the problem is that my table is displaying a large number of rows, so I made a javascript filter to display only rows which match with the filter values
But the problem is I don't how to use row id and then use their values to get compared with the javascript variable and based on match its CSS property is set to display (if matched) or hide (if not matched).
Is there any other way to do this?
Here is Filter Section.
<div class='row'>
<div class='col'>
<label>Select Filters:</label>
</div>
</div>
<div class='row'>
<div class='col'>
<div class='filter'>
<label>EmpID:</label>
<select id='empid_select'>
<option value='' >select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `EmpID`, `Name` FROM `employee_data` ORDER BY `EmpID` ');
if($stmt->execute()){
$stmt->bind_result($empid, $empname);
while($stmt->fetch()){
echo "<option value='$empid'>$empid - $empname</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
$stmt->close();
?>
</select>
<label>Project Code:</label>
<select id='projectcode_select'>
<option value=''>Select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `Projectcode`, `Title` FROM `Projectcodetbl` ORDER BY `Projectcode` ASC ');
if($stmt->execute()){
$stmt->bind_result($projectcode, $title);
while($stmt->fetch()){
echo "<option value='$projectcode'>$projectcode - $title</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
?>
</select>
<label>Start Date: </label>
<input type='date' name='startdate-filter' id='startdate-filter' >
<label>End Date: </label>
<input type='date' name='enddate-filter' id='enddate-filter' >
<button name='notseen-entries-filter-button' id='notseen-entries-filter-button'>Apply</button>
</div>
</div>
</div>
Here is my script to get value form the filter section.
<script>
$(document).ready(function(){
$('[name="notseen-entries-filter-button"]').click(function(e){
var empid = $('#empid_select option:selected').val();
var projectcode = $('#projectcode_select option:selected').val();
var startdate = $('#startdate-filter').val();
var enddate = $('#enddate-filter').val();
alert("Filter rows with values EmpID: "+empid+", ProjectCode: "+projectcode+", StartDate: "+startdate+", EndDate: "+enddate);
});
});
</script>
PHP Function for displaying the table heading
function displayTableHeading(){
echo "
<form action='selected.php' method='post'>
<table border='1' cellpadding='10' cellspacing='0'>
<tr>
<th colspan='13'><button type='submit' class='btn btn-outline-primary' style='border-radius: 3px;'><i class='fas fa-edit' style='margin-right:10px;'></i>Update</button>
</tr>
<tr>
<th>Row</th>
<th>EmpID - Name</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Hrs</th>
<th>Project Code</th>
<th>Task Performed</th>
<th>Invoice Num</th>
<th colspan=3>Status</th>
</tr>";
}
PHP Function for displaying the table rows.
//Webpage Table Row
function displayTableRow($row, $i, $empid){
$notBillable = intval( $row['Status'] )==1 ? 'checked' : '';
$billablePlusNotInvoiced = intval( $row['Status'] )==2 ? 'checked' : '';
$billablePlusInvoiced = intval( $row['Status'] )==3 ? 'checked' : '';
printf("
<!-- record: %d -->
<tr id='%d'>
<td><input type='text' size='1' value='%d' ></td>
<td><input type='text' size='10' name='empid[]' value='%s'></td>
<td><input type='text' size='7' name='date[]' value='%s' ></td>
<td><input type='text' size='5' name='stime[]' value='%s' ></td>
<td><input type='text' size='5' name='etime[]' value='%s' ></td>
<td><input type='text' size='1' name='hours[]' value='%s' ></td>
<td><b><input type='text' size='9' name='projectcode[]' value='%s' ></b></td>
<td><input type='text' size='30' name='taskperformed[]' value='%s' ></td>
<td><input type='text' size='8' name='invoicenum[]' value='%s' ></td>
<td><input type='radio' name='status_{$i}[]' value='1' %s/>NB</td>
<td><input type='radio' name='status_{$i}[]' value='2' %s/>B+NI</td>
<td><input type='radio' name='status_{$i}[]' value='3' %s/>B+I</td>
<input type='hidden' name='modifieddate[]' value='%s'>
</tr>",
$i,$i,$i,
getEmpNameById($empid),
$row['Date'],
$row['StartTime'],
$row['EndTime'],
$row['NoOfHours'],
$row['ProjectCode'],
$row['TaskPerformed'],
$row['InvoiceNumber'],
$notBillable,
$billablePlusNotInvoiced,
$billablePlusInvoiced,
$row['ModifiedDate']
);
}
PHP code for calling above function and displaying the HTML table.
$sumNoOfHours = 0.0;
displayTableHeading();
$i=1;
foreach($empid_array as $code){
//split the $code variable to get the emp id
$codearr = explode(" - ", $code);
$empid = $codearr[0];
$selectSql = "SELECT * FROM `mastertbl` WHERE EmpID = '$empid' AND Status = 0 ORDER BY Date DESC, ModifiedDate DESC";
$result = mysqli_query($conn, $selectSql) or die( mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$sumNoOfHours = $sumNoOfHours + $row['NoOfHours'];
displayTableRow($row, $i, $empid);
$i++;
}
}

Get row index of a table javascript

I know this question has been asked many times, I went through most of the suggestions and none of the solutions seem to be working for me.
I have a table in a modal in which I am allowing the user to make some changes. I then use these values to update the data in the database.
My table rows are created by echoing the HTML code
echo "<tr> ";
echo "<td > $row_counter </td>";
echo "<td style='width:200px' class='left_align' > $lstr_product_name </td>";
echo "<td > $lstr_department_name </td>";
echo "<td > <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='$lint_unit_cost' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='$lint_product_id' type='hidden'/> </td>";
echo "<td > $lint_quantity_counted </td>";
echo "<td > $lint_total_cost </td>";
To update the proper values in the database I need to get the product_id name which I know that I can get by
var x = document.getElementsByName("product_id")[0].value;
However I need to get the correct row index to be able to POST the correct product_id.
I have tried the following:
alert($(this).index());
But this always returns 0. The closest I got to a solution was by using
var rowID = $(this).closest('tr').index();
alert(rowID);
The problem with this is that my editable cell is "unit_cost" which is the 4th cell in the tr. This means that the closest tr is not the one that the row that the cell is in but the one below.
I have then tried
alert( "Row id: " + $("#tbl_store_product_sizes tr").this.rowIndex );
But also no luck. I have ran out of ideas, what is the proper way of doing this?
EDIT
All my javascript code is enclosed in the $(document).ready(function()
I am watching for the change of the unit_cost field using the following code
$(document.body).off( "change", ".unit_cost");
$(document.body).on('change', '.unit_cost', function(event)
{
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = document.getElementsByName("product_id")[rowID].value;
alert('The product id is: ' + x);
var unit_cost = document.getElementsByName("unit_cost")[rowID].value;
});
Explanation:-
Since both inputs are in the same <td>, so on change of first-one you have to use .next() to get next input data.
You need to do it like below:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert(rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
Working snippet:-
$(document).on('change', '.unit_cost', function(event) {
var rowID = $(this).closest('tr').index();
alert('The corresponding row index is: '+ rowID);
var product_id = $(this).next('.product_id').val();
alert('The product id is: ' + product_id);
var unit_cost = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td style='width:200px' class='left_align'>2 </td>
<td>3 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='4' /> <input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='5' type="hidden"/> </td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td style='width:200px' class='left_align'>9 </td>
<td>10 </td>
<td> <input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='11' /><input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='12' type="hidden"/> </td>
<td>13</td>
<td>14</td>
</tr>
</table>

Cloning table row and adding it to end of table

I am trying to clone and append a table row when the user selects my add rows button. I have an empty hidden row that is used to clone. I can't seem to get it to work how I need it too.
I output my form with PHP and looks something like this:
$budgetRowCount = 0;
echo"<table id='selected_budget_table'>
<tr>
<th>Roofs</th>
<th>Roof Area</th>
<th>Recommendations</th>
<th>Amount</th>
<th>Remove</th>
</tr>";
echo "<tr id='new_budget_row0' style='display: none;'>
<td><input id='budget-roofs' name='budget-roofs[]' /></td>
<td><input id='budget-area' name='budget-area[]' /></td>
<td><input id='budget-recommendation' name='budget-recommendations[]' /></td>
<td><input id='budget-amount' name='budget-amount[]'/> </td>
</tr>";
while ($budgetInfoRow = mysqli_fetch_array($budgetResult)) {
if($budgetRowCount == 0){
echo "<tr id='selected_budget_row". $budgetRowCount ."'>";
echo "<td><input type='text' id='budget-roofs' name='budget-roofs[]' value='".$budgetInfoRow['budget_roofs']."'</td>";
echo "<td><input type='text' id='budget-roof-area' name='budget-roof-area[]' value='".$budgetInfoRow['budget_roof_area']."'</td>";
echo "<td><input type='text' id='budget-recommendation' name='budget-recommendation[]' value='".$budgetInfoRow['budget_recommendation']."'</td>";
echo "<td><input type='text' id='budget-amount' name='budget-amount[]' value='".$budgetInfoRow['budget_amount']."'</td>";
echo "</tr>";
$budgetRowCount++;
}
else{
echo "<tr id='selected_budget_row". $budgetRowCount ."'>";
echo "<td><input type='text' id='budget-roofs' name='budget-roofs[]' value='".$budgetInfoRow['budget_roofs']."'</td>";
echo "<td><input type='text' id='budget-roof-area' name='budget-roof-area[]' value='".$budgetInfoRow['budget_roof_area']."'</td>";
echo "<td><input type='text' id='budget-recommendation' name='budget-recommendation[]' value='".$budgetInfoRow['budget_recommendation']."'</td>";
echo "<td><input type='text' id='budget-amount' name='budget-amount[]' value='".$budgetInfoRow['budget_amount']."'</td>";
echo "<td><a href='#' class='removeRow' data-remove-row='budget_row". $budgetRowCount . "'>Remove</a></td>";
echo "</tr>";
$budgetRowCount++;
}
}
echo "</table>";
echo"<input type='button' value='+' id='addNewBudgetRow' class='addNewBudgetRow'/>";
And this is how I am attempting to clone my row and add it to my table:
$(function() {
var $removeIDVal = 0;
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRow = $("#new_budget_row0").clone();
$removeIDVal++
var $emptyBudgetTableRowClone = $emptyBudgetTableRow.clone();
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.children('td').last().after('<td>Remove</td>');
$(this).closest("fieldset").find("tbody").append($emptyBudgetTableRowClone);
$emptyBudgetTableRowClone.show();
});
});
I had an alert to check if the button was actually firing and my alert showed up no problem, however I can't seem to get it to clone and append properly and I have done this several times elsewhere with no issues. Where am I going wrong here?
How can I fix this so that my row gets cloned properly and added to the end of my table?
You are not selecting your table, since you have no <fieldset> or <tbody>. Select it by id.
Alos you were cloning new row twice and you have multiple same ids.
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRowClone = $("#new_budget_row0").clone();
$removeIDVal++
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.children('td').last().after('<td>Remove</td>');
$('#selected_budget_table').append($emptyBudgetTableRowClone);
$emptyBudgetTableRowClone.show();
});
});
$(function() {
var $removeIDVal = 0;
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRowClone = $("#new_budget_row0").clone();
$removeIDVal++
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.children('td').last().after('<td>Remove</td>');
// Select you table by id
$('#selected_budget_table').append($emptyBudgetTableRowClone);
$emptyBudgetTableRowClone.show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='selected_budget_table'>
<tr>
<th>Roofs</th>
<th>Roof Area</th>
<th>Recommendations</th>
<th>Amount</th>
<th>Remove</th>
</tr>
<tr id='new_budget_row0' style='display: none;'>
<td><input id='budget-roofs' name='budget-roofs[]' /></td>
<td><input id='budget-area' name='budget-area[]' /></td>
<td><input id='budget-recommendation' name='budget-recommendations[]' /></td>
<td><input id='budget-amount' name='budget-amount[]'/> </td>
</tr>
</table>
<input type='button' value='+' id='addNewBudgetRow' class='addNewBudgetRow'/>
I've put it up on jsFiddle and found + fixed some issues:
http://jsfiddle.net/lumpie/nprsdb2m/
$(function() {
var $removeIDVal = 0;
$(document.body).on('click', '.addNewBudgetRow', function () {
var $emptyBudgetTableRow = $("#new_budget_row0");
$removeIDVal++
var $emptyBudgetTableRowClone = $emptyBudgetTableRow.clone();
var $newRowID = 'added_budget_row' + $removeIDVal;
$emptyBudgetTableRowClone.attr('id', $newRowID)
$emptyBudgetTableRowClone.append('<td>Remove</td>');
$("#selected_budget_table").append($emptyBudgetTableRowClone);
// Logic to remove a row:
$emptyBudgetTableRowClone.find(".removeRow").click(function() {
$(this).parents("tr").remove();
});
$emptyBudgetTableRowClone.show();
});
});
Ah, just a minute too late, Rene Korss was slightly ahead of me.
But hey: I've included a little extra: logic to make the Remove button work :)

php html javascript wrong result

This is my code
<html>
<head>
<title>
Aplikasi KRS
</title>
</head>
<body>
<p>IPK : 1.xx</p>
<form name="formTes" method="post">
<script>
function cekKrs()
{
var jum_sks = 0;
for(var i=0; i<7; i++)
{
if(document.formTes.elements[i].checked)
jum_sks += mataKuliah;
}
document.formTes.fieldJumlah.value = jum_sks;
if(jum_sks > 15)
{
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
}
}
function cekKirim()
{
if(document.formTes.fieldJumlah.value > 15)
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
else
window.location.href = "tesform.html";
}
</script>
<table border="2">
<tr><th>Kode</th><th>Mata Kuliah</th><th>SKS</th><th><Pilihan/th></tr>
<?php
include "koneksi.php";
$sql = "SELECT * FROM mata_kul";
$query = $con->query($sql);
while($mataKuliah = $query->fetch_array())
{
echo "<tr><td>". $mataKuliah['kodeMK'] ."</td>";
echo "<td>". $mataKuliah['namaMK'] ."</td>";
echo "<td>". $mataKuliah['sks'] ."</td>";
echo "<script>var mataKuliah= ".$mataKuliah['sks']."</script>";
echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs()'></td>";
}
?>
<tr><td colspan="2" align="right">Jumlah SKS</td>
<td colspan="2"><input size="3" value="0" name="fieldJumlah" type="text" readonly="readonly"></td></tr></table>
<br>
<input type="button" name="tombolKirim" value="Kirim" onclick="cekKirim()">
</form>
</body>
</html>
My question is
"Why when i click checklist it show the last value of sks in jumlah SKS, not the sks checked value i click ? like when i click checklist which have value of 2 in sks it should show 2 not 8 in jumlah SKS"
Here's the image
Can you tell me where did i go wrong ? I'm still new
I guess you need send the checkbox obj as param to cekKrs() , and in function cekKrs evaluates if obj is checked to + or - the obj.value from total
Try this DEMO
HTML ( draft )
<table>
<!-- while($mataKuliah = $query->fetch_array())
{ -->
<tr>
<!-- echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs(this)' value='".$mataKuliah['sks']."'></td>"; // PHP -->
<td><input type='checkbox' onclick='cekKrs(this)' value='1'>1</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='2'>2</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='3'>3</td>
</tr>
<!-- } -->
</table>
<input size="3" value="0" name="fieldJumlah" id='fieldJumlah' type="text" readonly="readonly">
onclick='cekKrs(this)' sends checkbox obj , and you keep the mataKuliah's value inside the checkbox value
JS
function cekKrs(chkObj)
{
//Get current total
var jum_sks = parseInt(document.getElementById('fieldJumlah').value);
//Get checkbox value clicked
var mataKuliah = parseInt(chkObj.value);
//Evaluate check to + or -
if(!chkObj.checked)
{
mataKuliah = (mataKuliah * -1)
}
jum_sks += mataKuliah;
//Set new total
document.getElementById('fieldJumlah').value = jum_sks;
}

Adding a dropdown from database in a form

My questions are in the end of this referred as MY PROBLEMS. Please read the questions before you try to go through all the things I have written, so that I don't waste so much of your time.
I have a form where I need to enter certain values as
ITEM | QUANTITY | PRICE | DISCOUNT | TOTAL
Item 1 | 1 | 100 | 05 | 95
Item 2 | 4 | 250 | 10 | 900
Add more
Total : 995
On clicking the 'Add more' link, a new set of same input fields appear, and so forth.
Each subtotal is automatically calculated (95 and 900 in this case).
These sub totals are automatically added to get the final total (995 in this case).
The script I use to have the 'Add more' functionality is the following
<script>
$(document).ready(function() {
var InputsWrapper = $("#InputsWrapper");
var AddButton = $("#AddMoreFileBox");
var x = InputsWrapper.length;
var FieldCount = 1;
$(AddButton).click(function(e){
FieldCount++;
$(InputsWrapper).append('<tr><td><input class="item" type="text" name="item[]"></td><td><input class="qty" type="number" name="qty[]"></td><td><input class="price" type="number" name="price[]"></td><td><input class="discount" type="number" name="discount[]">%</td><td><input class="total" type="number" name="total[]" readonly ></td></tr>');
x++;
return false;
});
});
</script>
The following is the form I have.
<table id="InputsWrapper">
<tr>
<span class="small">Add More Field</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' type='text' name='item[]'></td>
<td><input class='qty' type='number' name='qty[]'></td>
<td><input class='price' type='number' name='price[]'></td>
<td><input class='discount' type='number' name='discount[]'>%</td>
<td><input class='total' type='number' name='total[]' readonly></td>
</tr>
<tr>
<td><input id='totaldp' type='number' name='totaldp' readonly</td>
</tr>
</table>
Now, I need to have an extra field called tax, which will be fetched using a drop down populated from a database with tax values. I need this tax value also to be displayed against each item as a dropdown
ITEM | QUANTITY | PRICE | DISCOUNT | TAX | TOTAL
This is the code I use to make the dropdown in the form
<td>
<?php
$query = mysqli_query($con, "SELECT * FROM `tax`");
echo '<select name="vat" class="vat">';
while ($row = mysqli_fetch_array($query)) {
echo '<option value="' . $row['tax_rate'] . '">' . $row['tax'] . '</option></br>';
}
echo '</select>';
?>
</td>
And in the script, I add class="vat" type="number" name="vat[]"
MY PROBLEMS:
Doing this way, I get the dropdown only once. Clicking the 'add more' field gives only an empty dropdown.
If anyone could help, let me know how.
I think this is very inefficient and stupid way of doing it, so if there is a better way, please let me know.
Please share how do you add the select to the append code. It seems that you are making something wrong there.
So i would recommend you this first the html and php:
<table id="InputsWrapper">
<tr>
<span class="small"><a onclick="addRow();" 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' type='text' name='item[]'></td>
<td><input class='qty' type='number' name='qty[]'></td>
<td><input class='price' type='number' name='price[]'></td>
<td><input class='discount' type='number' name='discount[]'>%</td>
<td>
<?php
$query = mysqli_query($con, "SELECT * FROM `tax`");
echo '<select name="vat" class="vat">';
while ($row = mysqli_fetch_array($query)) {
echo '<option value="' . $row['tax_rate'] . '">' . $row['tax'] . '</option></br>';
}
echo '</select>';
?>
</td>
<td><input class='total' type='number' name='total[]' readonly></td>
</tr>
<tr>
<td><input id='totaldp' type='number' name='totaldp' readonly</td>
</tr>
Note that for the "Add more button" i use a javascript function:
<script type="text/javascript"><!--
var module_row = <?php echo $module_row; ?>;
function addRow() {
html = '<tr>';
html+= '<td><input class='item' type='text' name='item[]'></td>';
html+= '<td><input class='qty' type='number' name='qty[]'></td>';
html+= '<td><input class='price' type='number' name='price[]'></td>';
html+= '<td><input class='discount' type='number' name='discount[]'>%</td>';
<?php $query = mysqli_query($con, "SELECT * FROM `tax`"); ?>
html += '<select name="vat" class="vat">';
<?php while ($row = mysqli_fetch_array($query)) { ?>
html += '<option value="<?php echo $row['tax_rate']; ?>">';
html += $row['tax'];
html += '</option></br>';
<?php } ?>
html += '</select>';
html+= '<td><input class='total' type='number' name='total[]' readonly></td>';
html+= '</tr>';
module_row++;
$(InputsWrapper).append(html);
}
//--></script>
I am very sorry for the code format and that there is no code check, but i am in work and have no time. If you can remove the js and code mistakes i did, it should work fine. If not i can make you a better solution when i am back home.

Categories