This is function which is reposible for create row dynamically.
$(document).ready(function() {
var count = 1;
var row = $("table#myTable tr:eq(1)");
$(document).on('click', '#addrow', function() {
$('#myTable tbody').append('<tr class="prototype" id="' + count + '"> <td align="center" ><input type="text" size="10" name="grnno[' + count + ']" id="grnno" class="required" align="right"/></td><td align="center" ><input type="text" name="paymentdateid="datepicker size="10" class="datepicker" align="right" /></td><td align="center"><select id="bankname" name="bankname"><option value="">Select Bank Name</option><option value="SBI">SBI</option><option value="UBI">UBI</option><option value="UCO">UCO</option><option value="HDFC">HDFC</option></select></td><td align="center" ><input type="text" name="amount[' + count + ']" id="amount[' + count + ']" size="10" class="required" align="right"/></td><td align="center"><input type="button" value="Delete" onclick="deleteRow(this)"></td><td style="display:none;"><input type="text" name="id[]" value="' + count + '" class="id" /></td></tr>');
count++;
});
});
now I want to attach this function with the field "Payment Date" as I need the datepicker dynamically
.
$(function() {
$( "#datepicker" ).datepicker({
inline: true
});
});
I have to mentioned here customizing the append function is not possible .
Since it is a widget, you need to initialize it once the element is added to the dom.
So
Use appendTo() to get back the tr that is added
use class for the datepicker instead of id since ID of an element must be unique
after appending the tr find the datepicker element and initialize the widget
Try
$(document).ready(function () {
var count = 1;
var row = $("table#myTable tr:eq(1)");
$(document).on('click', '#addrow', function () {
var $tr = $('<tr class="prototype" id="' + count + '"> <td align="center" ><input type="text" size="10" name="grnno[' + count + ']" id="grnno" class="required" align="right"/></td><td align="center" ><input type="text" name="paymentdate classs="datepicker size="10" class="datepicker" align="right" /></td><td align="center"><select id="bankname" name="bankname"><option value="">Select Bank Name</option><option value="SBI">SBI</option><option value="UBI">UBI</option><option value="UCO">UCO</option><option value="HDFC">HDFC</option></select></td><td align="center" ><input type="text" name="amount[' + count + ']" id="amount[' + count + ']" size="10" class="required" align="right"/></td><td align="center"><input type="button" value="Delete" onclick="deleteRow(this)"></td><td style="display:none;"><input type="text" name="id[]" value="' + count + '" class="id" /></td></tr>').appendTo('#myTable tbody');
$tr.find(".datepicker").datepicker({
inline: true
});
count++;
});
});
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 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('');
}
});
})
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"])
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" name="phone_1" class="inputs lst" id="phone_1" /></td>
</tr>
</table>
<script>
var i = $('table tr').length;
$('.lst').on('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$('.inputs').keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
</script>
In this form initially focus on first text box ,then press enter key it automatically focus to nearby input fields at dead end while we press enter Key then it create new row and focus to initial input field presented in newly created row
after that while we press enter key it doesn't focus to near by text field please help to resolve this issue.
In first row it work correctly while we entering second row it not working
please help
You need event delegation for dynamically generated elements like following.
var i = $('table tr').length;
$(document).on('keyup', '.lst', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" name="phone_1" class="inputs lst" id="phone_1" /></td>
</tr>
</table>
I have a html table which data is retrieved from database after that i can add new row to enter the data but the nummbering wont continues of last number, my question is how to increasing the numbering of the table, please see the pictere :http://imgur.com/quB1R2G
This is my javascript when the button + clicked the new row will append to the table
$('#btn_add_dependents').click(function(){
var i = 0;
i +=1;
$('#tbl_dependents_info').append(
'<tr class="odd"><td style="margin-left:10px;text-align:center;" class="no"></td> '
+'<td style="text-align:center;"><input id="dependents_name' + i + '" name="dependents_name[]" type="text" size="15" ></td>'
+'<td style="text-align:center;"><select id="dependents_gender'+ i + '" name="dependents_gender[]">'
+'<option value="1">Male</option>'
+'<option value="2">Female</option></select></td>'
+'<td style="text-align:center;"><select id="dependents_relationship'+ i + '" name="dependents_relationship[]">'+ relationship +'</select></td>'
+'<td style="text-align:center;"><input id="dependents_occupation' + i + '" name="dependents_occupation[]" type="text" size="15" ></td>'
+'<td style="text-align:center;"><input id="dependents_dob' + i + '" name="dependents_dob[]" type="date" ></td>'
+'<td style="text-align:center;"><input id="dependents_remark' + i + '" name="dependents_remark[]" type="text" size="20" ></td>'
+'<td style="text-align:center;"><img src="images/subtract.png" style="height:20px;" id="del" ></td>'
+'</tr>');
updateRowOrder();
return false;
});
function updateRowOrder() {
$('td.no').each(function (i) {
$(this).text(i + 1);
});
}
$( document ).on( "click", "#del", function() {
$(this).parent().parent().remove();
updateRowOrder();
});
});
This is function of retrieved the data from database and put in html table
$sql="SELECT name,gender,cust_dependent.relationship as relationship_id,relationship.relationship,occupation,d_o_b,remark
FROM cust_dependent
INNER JOIN relationship ON relationship.id = cust_dependent.relationship
WHERE cust_id = $customer_id AND createdby = $user_id ";
$query=$db->query($sql);
while ($row=$db->fetch_assoc($query)){
$i++;
$name=$row['name'];
$gender=$row['gender'];
$relationship_id = $row['relationship_id'];
$relationship=$row['relationship'];
$occupation=$row['occupation'];
$d_o_b=$row['d_o_b'];
$remark=$row['remark'];
$relationship=$slctrl->getSelectRelationship($relationship_id);
echo<<<EOF
<tr>
<td style="text-align:center;">$i</td>
<td class="odd" style="text-align:center;"><input id="dependents_name$i" name="dependents_name[]" type="text" size="15" value="$name"></td>
<td class="odd" style="text-align:center;"><select id="dependents_gender$i" name="dependents_gender[]">
<option value="1" $male>Male</option>
<option value="2" $female>Female</option></select></td>
<td class="odd" style="text-align:center;"><select id="dependents_relationship$i" name="dependents_relationship[]">$relationship</select></td>
<td class="odd" style="text-align:center;"><input id="dependents_occupation$i" name="dependents_occupation[]" type="text" size="15" value="$occupation" ></td>
<td class="odd" style="text-align:center;"><input id="dependents_dob$i" name="dependents_dob[]" type="date" value="$d_o_b"></td>
<td class="odd" style="text-align:center;"><input id="dependents_remark$i" name="dependents_remark[]" type="text" size="20"value="$remark" ></td>
EOF;}}
I can add the row now but the numbering is wrong its will start as 1, how to let it became continue number of last row?
ps:last row data is retrived from database.
You need to preserve the value(value here indicates number of rows present in your html table). When you retrieve the rows from database , then save the count in some variable , say $count. Set this $count variable in html input field(make it hidden) as
< input type="hidden" id="table-count" value="$count">
And in jquery
while adding row , do
$currentRowNo = parseInt($('#table-count').val())++; //get value
$('#table-count').val($currentRowNo) // update value
while deletion, simply subtract the value
$currentRowNo = parseInt($('#table-count').val())--; //get value
$('#table-count').val($currentRowNo) // update value
Try:
function updateRowOrder() {
var i = 1;
$('td.no').each(function () {
$(this).text(i);
i++;
});
}
Try increasing your index value on click of + button from the last index value you got from database.
You can preserve the last index value you got from database in a hidden field and also update this value on every click on + button.