I am generating dynamic textboxes on button click in a table.
On button click i am calling Details() which appends a new row to the table:
function Details(id,name)
{
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_id[]" value="'+ id +'" class="form-control item_id" autofocus required /></td>';
html += '<td><input type="text" name="item_name[]" value="'+ name +'" class="form-control item_name" required /></td>';
html += '<td style="text-align:center"><button type="button" name="remove" class="btn btn-danger btn-sm order_item_remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$("#table").append(html);
}
But when i try to live search the data from the table then its rows disappear.
Live Search:
$("#search_field").keyup(function() {
var count = 0;
var value = this.value.toLowerCase().trim();
$("#table").find("tr").each(function(index) {
if (index === 0) return;
var id = $(this).find("td").text().toLowerCase().trim();
$(this).toggle(id.indexOf(value) !== -1);
if(id.indexOf(value) !== -1){
count = count+1;
}
});
});
Table:
<table class="table table-bordered" id="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
What am i doing wrong?? Any help would be appreciated.
You can use this (edited to use non-ES6 syntax):
var rowMatches = $(this)
.find(':input')
.toArray()
.some(function(input) { return $(input).val().toLowerCase().trim().indexOf(value) !== -1; });
$(this).toggle(rowMatches);
Explanation
.text() is not meant to grab input vales.
You need to use .val(). But since there can be multiple inputs per rows, you want to check whether at least one cell matches the filter.
.toArray() transforms the set of nodes into an array,
Array#some returns true if at least one cell's value matches the filter string.
Demo using the rest of your code
$("#search_field").keyup(function() {
var count = 0;
var value = this.value.toLowerCase().trim();
$("#table").find("tr").each(function(index) {
if (index === 0) return;
var rowMatches = $(this)
.find(':input')
.toArray()
.some(function(input) { return $(input).val().toLowerCase().trim().indexOf(value) !== -1; });
$(this).toggle(rowMatches);
if (rowMatches) {
count = count + 1;
}
});
});
function Details(id, name) {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_id[]" value="' + id + '" class="form-control item_id" autofocus required /></td>';
html += '<td><input type="text" name="item_name[]" value="' + name + '" class="form-control item_name" required /></td>';
html += '<td style="text-align:center"><button type="button" name="remove" class="btn btn-danger btn-sm order_item_remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$("#table").append(html);
}
Details(1, 'foo');
Details(2, 'bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
<input id="search_field" placeholder="Filter"/>
Related
I have 2 functions. Add dynamic rows and Autonumbering. My problem is, my autonumbering is not working on my dynamically added rows. I wonder what could be the problem? The "class="form-control" is all the same for my input type field. However, it is still not working. I have provided my js fiddle below.
https://prnt.sc/124vuju
https://jsfiddle.net/rain0221/59k4c0yg/3/ // in "lb" column, type any number and hit ctrl+enter in order to do autonumbering
//this is my function for autonumbering
const inputs = document.querySelectorAll(".form-control");
inputs[0].addEventListener("keyup", e => {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic rows.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" id="auto" value="" class="form-control" type="number" readonly /></td>"' +
'<td><input id="weight' + rowIndex + '" name="weight' + rowIndex + '" type="number" /></td>"' +
'<td><input id="wingBand' + rowIndex + '" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="weight" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You need to find the elements inside eventListener event. Since you are finding the element global onload so if will not hold the elements added dynamically. You can move the blow code inside addEventListener keyup event.
const inputs = document.querySelectorAll(".form-control");
To attach the keyup event, you can use document.querySelectorAll(".form-control")[0] instead of inputs[0].
document.querySelectorAll(".form-control")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
I can see that you have assigned the 'form-control' class only for LB# column so autonumber will be generate only for LB#. In case you want to generate autonumber for all the columns, assign the class="form-control" to each added dynamically.
The problem is that you are addding keyup listeners only to those elements that are already present in the DOM at the time you are adding them.
What you need instead is called delegate listeners, and it means that you rely on the mechanism that most events bubble up in the DOM, allowing you to attach the keyup listener to an element that is an ancestor to all the input elements of interest.
Inside that listener, you then check if the element they event came from is one you want to handle.
//this is my function for autonumbering
const inputAncestor = document.querySelector("tbody");
inputAncestor.addEventListener("keyup", e => {
if (
e.target.matches('input.form-control') &&
((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10))
) {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
inputs.forEach((inp) => {
if (inp !== e.target) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic rows.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form-control" type="number" readonly /></td>"' +
'<td><input id="weight' + rowIndex + '" name="weight' + rowIndex + '" type="number" /></td>"' +
'<td><input id="wingBand' + rowIndex + '" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="weight" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=5><button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
Unfortunately, your code has several more problems, which I tried to fix.
As mentioned in the first comment to your question, you cannot have a div as a child of tbody. Only tr is allowed here.
You are using duplicate id value auto. That is invalid HTML.
In your markup, you have the class form-control on all the inputs. In your dynamically added markup it's only on the first input. Which version is the correct one?
In your tfoot you had the button as direct child. This is, again, invalid HTML. The only child element(s) tfoot can have is tr.
The very first row in your table describes the columns and acts as your table's header, yet it did not reside in the thead part of your table.
i have this code for add/remove dynamic input:
JS:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
var number = Math.random();
return '<td id="' + number + '"><input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><select name="" class="form-control"><option> Select</option><option> Male</option><option> Female</option></select></td>' + '<td><input name = "DynamicTextBox" type="radio" value = "' + value + '" /></td>' + '<td><input name = "DynamicTextBox" type="checkbox" value = "' + value + '" /></td>'+'<td><input name = "order" type="number" value = "" /></td>' + '<td><button type="button" class="btn btn-danger remove"><i class="fas fa-times"></i></button></td>'
}
HTML:
<p> </p>
<h5 class="text-center">Dynamic Control : Text Box, Dropdown List, Radiobox and Checkbox</h5>
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<td>TextBox</td>
<td>Dropdown List</td>
<td>Radio</td>
<td>CheckBox</td>
<td>Order</td>
<td>BTN</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="fas fa-plus"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
</section>
this code work true for me but how do can i add dynamic order(from 1 to ...) for each row(td). my mean add order input from number 1 and add +1 number from last order number.
demo is here
update: (my need)
You need to just modify the JS code logic. The below example shows the use of variable count and its usage.
Here, the variable count is declared as 1 initially and as per the "Add" click the count value has been incremented by 1. Same way the count is been decremented by 1 when we are deleting/removing the the "tr" column.
$(function () {
var count = 1;
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("", count));
$("#TextBoxContainer").append(div);
count++;
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
count--;
});
});
The click function will have one more argument count which is used for the rendering/displaying of the count value in the order field.
function GetDynamicTextBox(value, count) {
var number = Math.random();
return '<td id="' + number + '">
<input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" />
</td>' + '
<td>
<select name="" class="form-control">
<option> Select</option>
<option> Male</option>
<option> Female</option>
</select>
</td>' + '
<td>
<input name = "DynamicTextBox" type="radio" value = "' + value + '" />
</td>' + '
<td>
<input name = "DynamicTextBox" type="checkbox" value = "' + value + '" />
</td>'+'
<td>
<input name = "order" type="number" value = "' + count + '" /></td>' + '
<td>
<button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button>
</td>'
}
The above code works when we are removing the row from the last column.
If you are removing in-between the row from the list of tr tags you will find the order columns values are not arranged properly.
The below code is used for the removing the tr tag in-between the row and as well as the from the last tr tag. This code will be flexible for removing the tr row from anywhere in the list as well as updating the order row in the incremental way.
$("body").on("click", ".remove", function () {
var deleteElement = $(this).closest("tr");
var countOfDeleteElement = $(deleteElement).find("#order").val();
var lastElementCount = count - 1;
if (countOfDeleteElement !== lastElementCount) {
// It will come inside this if block when we are removing inbetween element.
var remainingElements = deleteElement.nextAll('tr'); // get all the below elemnts from the removing element.
// updating all remainingElements value of the order column
remainingElements.each((i, ele) => {
$(ele).find("#order").val(countOfDeleteElement);
countOfDeleteElement++;
})
}
deleteElement.remove();
count--;
});
I have problem. I use jquery to make dynamic input in php like this:
$(document).ready(function() {
var count = 0;
$("#add_btn").click(function(){
count += 1;
$('#container').append(
'<tr class="records">'
+ '<td ><div id="'+count+'">' + count + '</div></td>'
+ '<td><select class="form-control form-control-sm" name="site' + count + '" required><option value="">Input Item</option><option value="canon">canon</option><option value="nikon">nikon</option><option value="fuji">fuji</option></select></td>'
+ '<td><input name="codeitem' + count + '" type="text"></td>'
+ '<td><a class="remove_item" href="#" >Delete</a>'
+ '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden"></td>'
+ '</tr>'
);
});
$(".remove_item").live('click', function (ev) {
if (ev.type == 'click') {
$(this).parents(".records").fadeOut();
$(this).parents(".records").remove();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="id_form" action="save.php" method="post">
<table>
<tr>
<td>
<input type="button" name="add_btn" value="Add" id="add_btn">
</td>
</tr>
<tr>
<td>No</td>
<td>Item</td>
<td>Code Item</td>
<td> </td>
</tr>
<tbody id="container">
<!-- nanti rows nya muncul di sini -->
</tbody>
<tr>
<td>
<input type="submit" name=submit value="Save">
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</form>
Condition: If I chose canon in combo select menu, then at input codeitem show code of the item (in another case, I use PHP to get codeitem from SQL table.
At first row input field, that was success.. but, if I want add more input field with click 'add button' to entry another item (at second row input field), why first input codeitem change code item, not input codeitem at second row?
How can I input dynamic item with that condition?
If you are not working on a legacy code base then it is batter to use latest version of Jquery.
'<td ><div id="'+count+'">' + count + '</div></td>' , you can't use same id in multiple time, so change it to class.
'<td><input name="codeitem' + count + '" type="text"></td>' ,input field name should be fixed in order to process it in your php script after form submit but as you need to get multiple value make it an array codeitem[]
what is the use of rows[] input field?
To input codeitem dynamically on change combo select menu, you have to use "Ajax" to get the 'codeitem' value of the selected combo menu from your database.
Check this jsfiddle .
$(document).ready(function() {
$("#add_btn").click(function(){
let count = $('tr.records').length+1;
$('#container').append(
'<tr class="records">'
+ '<td ><div class="count">' + count + '</div></td>'
+ '<td><select class="site form-control form-control-sm" name="site[]" required><option value="">Input Item</option><option value="canon">canon</option><option value="nikon">nikon</option><option value="fuji">fuji</option></select></td>'
+ '<td><input class="codeitem" name="codeitem[]" type="text"></td>'
+ '<td><a class="remove_item" href="#" >Delete</a>'
+ '<input class="rows" name="rows[]" value="'+ count +'" type="hidden"></td>'
+ '</tr>'
);
});
$(document).on('click',".remove_item", function (ev) {
$(this).parents(".records").fadeOut();
$(this).parents(".records").remove();
//Re-arrange the Row Serial No
$('tr.records div.count').each(function(index) {
$(this).text(index+1)
});
});
$(document).on('change',".site", function (ev) {
let site = $(this).val();
let current = $(this).parents(".records");
if(site!=''){
//make an ajax call to get the corresponding CodeItem of the selected site
/* $.ajax({
url: "/yoururl",
data:{"id":site},
success: function(result){
$(current).find('.codeitem').val(result);
}
}); */
}else{
$(current).find('.codeitem').val('');
}
});
})
I wish to validate a simple table form using jquery. So far I have a for loop that loops through all the fields and checks if they are empty. Then I have another for loop that checks to see if the age is within a certain range. And finally, the last loop checks to see if the email is in the correct RegEx pattern.
Currently only the first loop is working while the others are not being looped through. I have tried to do console.logs and it confirmed that the other loops are not being touched. Any ideas or help would be appreciated!
Semi working Code pen: https://codepen.io/anon/pen/ZXVmQz?editors=1010
Code:
HTML
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered" id="data-table">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>Email</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
JQuery
function validate(input) {
var isValid;
var filter = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var email = $('.email').val();
var length = $('.data').length;
console.log($('.email').val());
var rowInputLength = $("#TextBoxContainer input").length;
for (var i=0; i<rowInputLength; i++) {
if (!($(input[i]).val() == "" )) {
isValid = true;
validBorder($(input[i]));
if ($('input[type=number]') && !($(input[i]).val()<= 2 || $(input[i]).val() >= 100)) {
isValid = true;
console.log($('#age').val());
validBorder($(input[i]));
}
if ('$(input[i][type=email])' && filter.test(email)) {
isValid = true;
validBorder($(input[i]));
}
}
else {
isValid = false;
invalidBorder($(input[i]));
}
}
return isValid;
}
How the table is created
function GetDynamicTextBox(value1, value2, value3) {
return '<td><input name = "DynamicTextBox" id="name" type="text" value = "" placeholder = "' + value1 + '" class="form-control data" /></td>' +
'<td><input name = "DynamicTextBox" id="age" type="number" min="3" max="100" value = "" placeholder = "' + value2 + '" class="form-control data" /></td>' +
'<td><input name = "DynamicTextBox" id="email" type="email" value = "" placeholder="' + value3 + '" class="form-control data email" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button><button type="button" class="btn btn-success edit"><i class="glyphicon glyphicon-ok"></i></button></td>';
}
When this button is pressed:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("Enter Name", "Enter Age", "Enter Email"));
$("#TextBoxContainer").append(div);
$('#btnAdd').attr("disabled", "disabled");
$(".data").blur(function() {
validate($(this))
});
});
});
You lacked the relevant piece of code in the question, had to find it in your pen.
In your anonymous "Add Row" function you need to call validation with all of the input fields, using the selector you attempted to use can be done like so:
validate( $( ".data" ) )
Also other issues found in validate method: $(input[i]).val() is a string, convert it to a number using prefix +, +$(input[i]).val()
Every thing is working expect that on adding the dynamic fields,the input added is not captured into the array.Only the values in the only created input are read. HTML PART
<table class="table table-bordered table-hover order-list" >
<thead>
<tr><td>Product</td><td>Price (Ksh.) </td><td>Qty</td><td> (Ksh.)</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" name="product[]" required="" /></td>
<td><input type="text" class="form-control" name="price[]" required/></td>
<td><input type="text" class="form-control" name="quantity[]" /></td>
<td><input type="text" name="linetotal[]" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: Ksh.<input type="text" name="grandtotal" readonly="readonly" /><span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
THE javascript to sum up the get the sub total and grand total is as below:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td><input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="quantity' + counter + '"/></td>';
cols += '<td><input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="quantity"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="quantity"]').val();
var linetotal = +row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
the php part to read the array is
if(isset($_POST['cinvoice']) && $_SERVER["REQUEST_METHOD"] == "POST" &&is_array($_POST["product"]) && is_array($_POST["quantity"]) && is_array($_POST["price"]) && is_array($_POST["linetotal"]))
{
$recordid="";
$firstname="";
$product="";
$quantity="";
$price="";
$linetotal="";
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
foreach ($_POST["quantity"] as $key => $qty){
$quantity.=$qty. ",";
}
foreach ($_POST["price"] as $key => $prc) {
$price.=$prc. ",";
}
foreach ($_POST["linetotal"] as $key => $linetotal) {
$linetotal.=$linetotal. ",";
}
you should pass textbox name as an array:
cols += '<td><input type="text" name="product[]"/></td>';
cols += '<td><input type="text" name="price[]"/></td>';
cols += '<td><input type="text" name="quantity[]"/></td>';
cols += '<td><input type="text" name="linetotal[]" readonly="readonly"/>
Also you can use implode function in php
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
to
$product = implode(',', $_POST["product"])