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.
Related
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--;
});
How can I get dynamically added rows id's and user entered data? I have created a dynamic table but I don't know how to get the values and dynamically generated id's. Can anyone please help me?
$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) { //Get all tags with [data-action="sumDebit"]
var val = parseFloat(e.value); //Get int value from string
if (!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
total += val;
});
$('#totaldbt').val(total); //Update value to total
});
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><select class="form-control" id=' + cashacc + ' ' + FieldCount + '></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' ' + FieldCount + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" data-action="sumDebit" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' ' + FieldCount + '/></td><td style="width: 4%"><img src="./img/delete.svg" class="dlt-icon" ' + FieldCount + '></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<thead>
<tr>
<th>A/c Code</th>
<th>Account Name*</th>
<th>Narration*</th>
<th>Debit*</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr id="fst_row" class="jsrow">
<!-- First row -->
<td>
<input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control narate" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" data-action="sumDebit" value="100" class="form-control" name="cashdeb" readonly/>
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly/>
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
</tbody>
</table>
FIDDLE Here..
What do you mean by ids?? on what action you would want user data and ids of dynamically created rows.
Everything is there. You have jsrow enter code hereclass for each tr created. Fetch all tr and then fetch each input value as you have distinct class for each input.
var rows = $('#cashTable').find('tr.jsrow'); // get all rows.
Then iterate rows as per your need. i am writing directly lets say want to get all ids of row 2. Find all inputs under that row as below and then get id attribute.
var inputs = $(rows[0]).find('input'); // all inputs. same way all select as well
// iterate all inputs and grab ID attribute
for(let i =0 ; i< inputs.length; i++ ) {
var attr = inputs[i].getAttribute('id');
console.log(attr); // id attribute
console.log(inputs[i].value); // value
}
You can get user input by referring to the column and row inside a table
var table = document.getElementById("cashTable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseFloat(table.rows[i].cells[5].innerHTML);
//here cells is referred to the cell number you want the value if you want the value of all cells of a row then loop through the cells of a row
}
alert(sumVal);
console.log(sumVal);
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('');
}
});
})
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++;
});
});
With the SO community I have got a script that adds rows with unique names to a table. I want to take two inputs on each row and multiply them together and display result in a third input.
the fiddle is at http://jsfiddle.net/yUfhL/231/
My code is:
HTML
<table class="order-list">
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
<tr>
<td><input type="text" name="product" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="qty" /></td>
<td><input type="text" name="linetotal" /></td>
</tr>
</table>
<div id="grandtotal">
Grand Total Here
</div>
JS
var counter = 1;
jQuery("table.order-list").on('change','input[name^="product"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" name="product' +
counter + '"/></td><td><input type="text" name="price' +
counter + '"/></td><td><input type="text" name="qty' +
counter + '"/></td><td><input type="text" name="total' +
counter + '"/></td><td><a class="deleteRow"> x </a></td></tr>');
jQuery('table.order-list').append(newRow);
});
jQuery("table.order-list").on('click','.deleteRow',function(event){
$(this).closest('tr').remove();
});
$('table.order-list tr').each(function() {
var price = parseInt( $('input[id^=price]', this).val(), 10 );
var qty = parseInt( $('input[id^=qty]' , this).val(), 10 );
$('input[id^=linetotal]', this).val(price * qty);
});
So currently I cant get the js to fire that gets the product of the two cells, qty and price. I want to display result in linetotal.
The last part of this would be to display the sum of all linetotals as a grand total in the div grandtotal
Help appreciated as always.
You're only giving the elements a name attribute, but using the id selector ([id^=price]). It's much easier to give them a specific class than having to use that "id starts with" selector. Also, when do you want the line totals to be calculated? And when do you want the grand total to be calculated? On what event(s)?
Here's my interpretation of how it should look:
<table class="order-list">
<thead>
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="product" /></td>
<td>$<input type="text" name="price" /></td>
<td><input type="text" name="qty" /></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: $<span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
And the JS:
$(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="qty' + 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^="qty"]', 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^="qty"]').val();
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));
}
http://jsfiddle.net/QAa35/
In your JS, you weren't using linetotal for the one dynamic input's name. There were other several minor modifications I made. You might as well use <thead>, <tbody> and <tfoot> since you do have those sections in the <table>. Also, I don't think it's a good design to have a new row automatically added when the "product" inputs are changed. That can happen often, and their intent may not be to add a new product...a button is much more friendly. For example, say you type in "asdf" to the first "product" input, then click somewhere. A new row is added. Say you made a typo so you go back and change it to "asd", then click somewhere. Another new row is added. That doesn't seem right.
This function should do the trick:
function updateGrandTotal() {
var prices = [];
$('input[name^="price"]').each(function () {
prices.push($(this).val());
});
var qnts = [];
$('input[name^="qty"]').each(function () {
qnts.push($(this).val());
});
var total = 0;
for(var i = 0; i < prices.length; i++){
total += prices[i] * qnts[i];
}
$('#grandtotal').text(total.toFixed(2));
}
You just need to bind it to the table change event to update the grand total every time an input changes:
$("table.order-list").change(updateGrandTotal);
Here is a working fiddle.