<form id="form1" name="form1" method="post" action="">
<table width="100%" border="1" cellspacing="0" cellpadding="0" id="mans">
<tr>
<td>
<input type="text" name="item[]" id="11" />
</td>
<td>
<input type="text" name="recommendations[]" id="12" />
</td>
<td>
<input type="text" name="importance[]" id="13" />
</td>
<td>
<input type="text" name="quantity[]" id="14" />
</td>
</tr>
</table>
add row
http://jsfiddle.net/yKjuw/283/
I have been going through most of these questions and as I have no idea what I am doing. Using the fiddle above you can see the name attribute amends to to ID of the FIRST table td. I need the name of each column to remain the same going down. I tried to add other variables with td:second td:third but the function failed to work at all. Can anyone assist?
You can get the name of the input based on the last row and index of current input element like
function addTableRow(jQtable) {
var $row = jQtable.find("tr:last"),
$inputs = $row.find('input');
var lastId = $row.find("td:first input").attr("id");
var newId = parseInt(lastId) + 10;
var row = $('<tr />');
for (var i = 0; i <= 2; i++) {
var thisId = newId + i;
var cell = $('<td />');
var label = $('<label for="' + thisId + '">' + thisId + '</label>');
var input = $('<input type="text" name="' + $inputs.eq(i).attr('name') + '" id="' + thisId + '" />');
cell.append(label, input);
row.append(cell);
}
row.append('<td>del</td>');
jQtable.append(row);
}
Demo: Fiddle
You can use .clone() to simplify this
function addTableRow(jQtable) {
var $row = jQtable.find("tr:last"),
$clone = $row.clone().appendTo(jQtable);
$clone.find('[id]').attr('id', function(i, id) {
return 10 + +id;
});
$clone.find('label').remove();
$clone.find('input').each(function() {
$(this).before('<label for="' + this.id + '">' + this.id + '</label>')
})
}
Demo: Fiddle
Or this: Fiddle
Use clone, its simple. jQuery clone
function addTableRow(e) {
var row = $('#mans tr:last');
row = row.clone(true);
row.find('>td>input').each(function(){
var t = $(this), id = t.attr('id'), new_id = id*1+10;
t.attr('id',new_id);
});
$('#mans').append(row);
}
function removeRow(e){
e.preventDefault();
$(this).parents('tr').remove();
}
$(function () {
$('#addRow').on('click', addTableRow);
$('table tr>td>a').on('click', removeRow);
});
Related
I have 3 fields with inputs:
<div class="row">
<input onblur="calc_basic_amount();" id="rate_basic"></input>
<input onblur="calc_basic_amount();" id="qty_basic"></input>
<input id="basic_amount"></input>
</div>
Multiply rate_basic by qty_basic with js:
function calc_basic_amount(){
var qty_basic = document.getElementById('qty_basic').value;
var rate_basic = document.getElementById('rate_basic').value;
var basic_amount = (qty_basic * rate_basic);
document.getElementById('basic_amount').value = basic_amount.toFixed(2);
}
It works fine, but I have a button that add a row with the same inputs and the same id, but the calculation only works with the first row. How to make it work with all inputs? thanks
Add function to row:
function add_row_to_table() {
table_row += '<td><input id="qty_basic" type="number" min="0" onblur="calc_basic_amount();" onchange="calc_basic_amount();" data-quantity name="newitems[' + item_key + '][qty]" value="' + data.qty + '" class="form-control">';
table_row += '<input type="text" placeholder="' + app.lang.unit + '" name="newitems[' + item_key + '][unit]" class="form-control input-transparent text-right" value="' + data.unit + '" >';
table_row += '</td>';
table_row += '<td class="rate"><input id="rate_basic" type="number" data-rate data-toggle="tooltip" title="' + app.lang.item_field_not_formatted + '" onblur="calc_basic_amount();" data-rate onchange="calc_basic_amount();" name="newitems[' + item_key + '][rate]" value="' + data.rate + '" class="form-control"></td>';
table_row += '<td class="amount_basic" align="right"><input id="basic_amount" class="form-control"></td>';
table_row += '<td><i class="fa fa-trash"></i></td>';
table_row += '</tr>';
}
You should add dynamic id
<div class="row">
<input onblur="calc_basic_amount(1);" id="rate_basic1"></input>
<input onblur="calc_basic_amount(1);" id="qty_basic1"></input>
<input id="basic_amount1"></input>
</div>
Now when you create New Row
<div class="row">
<input onblur="calc_basic_amount(2);" id="rate_basic2"></input>
<input onblur="calc_basic_amount(2);" id="qty_basic2"></input>
<input id="basic_amount2"></input>
</div>
function calc_basic_amount(id){
var qty_basic = document.getElementById('qty_basic'+id).value;
var rate_basic = document.getElementById('rate_basic'+id).value;
var basic_amount = (qty_basic * rate_basic);
document.getElementById('basic_amount'+id).value = basic_amount.toFixed(2);
}
https://codepen.io/flakerimi/pen/xxgVpWR
I have simplified a bit but you get the idea.
var table = document.getElementById('myTable');
var rowCount = table.rows.length;
function addRow() {
currentNum = rowCount+1;
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = '<input onblur="calc_basic_amount('+currentNum+');" id="rate_basic'+currentNum+'" />';
cell2.innerHTML = '<input onblur="calc_basic_amount('+currentNum+');" id="qty_basic'+currentNum+'"/>';
cell3.innerHTML = '<input id="basic_amount'+currentNum+'"/>';
rowCount++;
}
function calc_basic_amount(id){
var qty_basic = document.getElementById('qty_basic'+id).value;
var rate_basic = document.getElementById('rate_basic'+id).value;
var basic_amount = (qty_basic * rate_basic);
document.getElementById('basic_amount'+id).value = basic_amount.toFixed(2);
}
table, td {
border: 1px solid black;
}
<p>Click the buttons to create and delete row(s) for the table.</p>
<table id="myTable">
<tr>
<td><input onblur="calc_basic_amount(1);" id="rate_basic1" /></td>
<td><input onblur="calc_basic_amount(1);" id="qty_basic1"/></td>
<td><input id="basic_amount1"/></td>
</tr>
</table>
<br>
<button onclick="addRow()">Create row</button>
<script>
</script>
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--;
});
<html>
<body>
<h1>RECEIPT</h1>
<datalist id="codes">
<?php
require_once('../../../mysqli_connect.php');
$query = "SELECT DISTINCT itemcode FROM itemcost";
$response = #mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($response)){
echo '<option value="' . $row['itemcode'] . '">';
}
?>
</datalist>
<form action="receipt.php" method="POST">
<table cellspacing="10" id="tbl">
<thead>
<td>ITEM CODE:</td>
<td>ITEM NAME: </td>
<td>QUANTITY OF ITEM:</td>
</thead>
<tbody>
<tr>
<td><input type="text" list="codes" name="Item_Code1" id="setter" size="5" /></td>
<td><input type="text" name="Item_Name1" id="receiver" size="10" /></td>
<td><input type="text" name="Quantity_In1" size="5" /></td>
</tr>
</tbody>
</table>
<br>
<br>
<input type="number" name="rows" id="addrows" />
<button type="button" id="btn">Add More</button>
<input type="submit" name="submitted" value="Enter" />
<input type="text" name="sendtotalrows" id="totalrows" style="visibility:hidden"/>
</form>
<script src="jquery.js"></script>
<script>
$(function(){
window.rowcompare = 2;
window.previousrownumber = 1;
$('#setter').change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $('#setter').val();
$('#receiver').val(itemcodename[selectedItemCode]);});});
$('#btn').on('click', function(){
var rownumber = $('#addrows').val();
rownumber = parseInt(rownumber) + window.previousrownumber;
while( rownumber >= rowcompare){
$('#tbl').find('tbody').append("<tr><td><input type=\"text\" list=\"codes\" name=\"Item_Code" + rowcompare +"\" id=\"setter" + rowcompare +"\" size=\"5\" /></td><td><input type=\"text\" name=\"Item_Name" + rowcompare +"\" id=\"receiver" + rowcompare +"\" size=\"10\" /></td><td><input type=\"text\" name=\"Quantity_In" + rowcompare +"\" size=\"5\" /></td></tr>");
$("#setter" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + rowcompare).val();
$("#receiver" + rowcompare).val(itemcodename[selectedItemCode]);});});
rowcompare++;
}
previousrownumber = rownumber;
$('#totalrows').val(previousrownumber);
});
});
</script>
</body>
</html>
My problem lies in this part of the code inside the while loop where I try to concatenate a variable to the Selector.
getitemcode.php just returns a key-value pair
$("#setter" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + rowcompare).val();
$("#receiver" + rowcompare).val(itemcodename[selectedItemCode]);
});
});
As the title says, my event won't trigger. I've seen similar questions asked and below are the answers I've tried:
var IcodeID = 'setter' + toString(rowcompare)
var InameID = 'receiver' + toString(rowcompare)
$("#" + IcodeID ).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#" + IcodeID ).val();
$("#" + InameID ).val(itemcodename[selectedItemCode]);
});
});
parseInt(rowcompare);
$("#setter" + ${rowcompare}).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + ${rowcompare}).val();
$("#receiver" + ${rowcompare}).val(itemcodename[selectedItemCode]);
});
});
parseInt(rowcompare);
$("#setter" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + rowcompare).val();
$("#receiver" + rowcompare).val(itemcodename[selectedItemCode]);
});
});
But the thing is when I try this:
$("#setter" + 2).change(function(){ $.getJSON('getitemcodename.php', function(itemcodename) {
var selectedItemCode = $("#setter" + 2).val();
$("#receiver" + 2).val(itemcodename[selectedItemCode]);
});
});
It works. Any help would be appreciated.
I got the solution from this link:
Passing variable to :eq jquery selector in a while loop
You need to wrap the Jquery code that uses the incremented variable inside this:
(function(rowcompare){ Jquery Code })(rowcompare);
Like so:
(function(rowcompare){
$(".code-input" + rowcompare).change(function(){ $.getJSON('getitemcodename.php', function(itemcodenamestocks) {
var selectedItemCode = $(".code-input" + rowcompare).val();
$(".code-output" + rowcompare).val(itemcodenamestocks[0][selectedItemCode]);
$(".stocks-output" + rowcompare).val(itemcodenamestocks[1][selectedItemCode]);
});
});
})(rowcompare);
And it works.
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 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"/>