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--;
});
Related
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('');
}
});
})
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"/>
<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);
});
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.