Dynamically add rows and run the script - javascript

I have a table that's creating rows dynamically upon button click. This input box contains an auto suggest script. When , I am trying to perform an input on the the first box(the one that is default created) , the auto complete works fine. But, on performing the dynamic adding of the row, the script for that row doesn't work. How to invoke the auto complete script on the new ?
<html>
<body>
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr>
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
{!! Form::text('nameId', null,['class'=>'form-control auto', 'placeholder' => 'name']) !!}
</td>
</tr>
</body>
</table>
<script type="text/javascript">
$(document).ready(function ()
{
$("#add").click(function()
{
$('#tableAdd tr:last').after('<tr><td>{!! Form::text('project_manager_name', null,['class'=>'form-control pmID', 'placeholder' => 'Project Manager']) !!}</td></tr>')
});
});
$(".auto")
.on("keydown", keyDownEventForProjectAndCompetencyLead)
.autocomplete(
{
//function that autocompletes the input
});
</script>
</body>
</html>

Jquery sometimes has a little trouble identifying elements that have been programatically added to the DOM just by the original class / id. Try using a different selector method to check against the modified page:
$(document)
.on("keydown", ".auto", keyDownEventForProjectAndCompetencyLead)
.autocomplete( // etc )

Your selector isn't applying to DOM elements added after the page is loaded.
Modify as above to listen on all element in document that match, or attach listener on each new element created:
<html>
<body>
<button id="add">add</button>
<table id="cooltable">
<tr>
<td>cool table cell</td>
</tr>
</table>
<script type="text/javascript">
function autoPopulate(event){
// some code
event.currentTarget.value = "auto populated content";
}
let add_button = document.getElementById('add');
add_button.addEventListener('click',(event)=>{
let new_row = document.createElement('tr'); // create row
let new_cell = document.createElement('td'); // create cell
let new_input = document.createElement('input'); // create input
new_input.type = 'text';
new_input.value = "default content";
new_input.addEventListener('keydown', (event)=>{ // attach listener
autoPopulate(event);
});
new_cell.appendChild(new_input) // add input to cell
new_row.appendChild(new_cell) // add cell to row
document.getElementById('cooltable').appendChild(new_row); // add row to table
})
</script>
</body>
</html>

Problem here is you are adding callback on "keyDown" event which is not happening hence your script is not running
To fix this you should add eventlistener on jquery load()
Or you should using .bind('DOMNodeInserted DOMNodeRemoved') to call function when new node are added or deleted.
<div id='myParentDiv'> </div>
<button>Click </button>
$("button").click(function(){
$("#myParentDiv").append("<div class='test'></div>");
});
$("#myParentDiv").bind("DOMNodeInserted",function(){
alert("child is appended");
});
Here is working demo
https://jsfiddle.net/vickykumarui/28edcsmb/
Code for Table Example
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr id = "test1">
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
Test 1
</td>
</tr>
</body>
</table>
var numberOFRow = 1;
$("#add").click(function(){
numberOFRow++
$('#tableAdd tr:last').after('<tr id = test'+numberOFRow +'><td> Test' + numberOFRow + '</td></tr>')
});
$("#tableAdd").bind("DOMNodeInserted",function(){
alert("Row number"+ numberOFRow+ "created");
});
Working Demo for your table examplehttps://jsfiddle.net/vickykumarui/qpxL8k4c/

Related

Delete row using inout field

I am creating table, and want to remove row by id using input field. (if input field matches with id then the row must be deleted)
can not figure it out.
Your help is much appreciated
`
<body onload="addRow()">
<table id="myTable" style="display:none">
<tr>
<th class="borderless">ID</th>
<th>Name</th>
<th>Username</th>
<th>Gender</th>
<th>Country</th>
</tr>
<tbody id="myTableBody">
</tbody>
</table>
<button type="button" id="buttonShow" onclick="showTable()">Show Table</button>
<button type="button" id="buttonAdd" onclick="addRow()" disabled>Add a new row</button>
<br>
<label>
<input class="input1" type="text" name="todoTags"/>
<button class="dellbtn" id="buttonDell"onclick="delRow()" disabled>Delete row</button>
</label>
`
`
function showTable(){
document.getElementById("myTable").style.display = "block";
document.getElementById("buttonAdd").disabled = false;
document.getElementById("buttonDell").disabled = false;
}
const btn = document.querySelector('.dellbtn')
const userTags = []
`
Here is my: JSfiddle
What you could do is changing the addRow() method so it adds a data-attribute to each row, in the <tr>. You can achieve this goal by adding this when creating the row :
row.setAttribute("row-id", tr.length - 1);
Then, when you want to delete it, you can simply search the
row that has the data-attribute that you just input. And it will look like this :
function delRow() {
const value = document.getElementById("valueToDelete").value;
document.querySelector('[row-id="' + value + '"]').remove();
}
I created a fork to your JSFiddle that you can check right here.
Hope it helps ! Good luck :)
Not exactly what you're asking, but this method might work better for you. It uses a delete button for each row so you can decide which one to delete. Then it uses a delegate listener to enable the delete buttons
const table = document.querySelector('#theTable tbody');
let c = 1
const addRow = () => {
table.innerHTML += `<tr><td>${c} data</td><td>${c} data</td><td><button class='delete'>delete</button></td></tr>`;
c++
}
// delegate listener for the delete button
table.addEventListener('click', e => {
if (e.target.classList.contains('delete')) {
e.target.closest('tr').remove();
}
})
<table id='theTable'>
<th>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td></td>
</tr>
</th>
<tbody>
</tbody>
</table>
<button onclick='addRow()'>Add Row</button>

Renaming ID of all child elements after dynamically deleting line in table

I created a form in Google Apps Script, to send data to a sheet, but I wanted a way to dynamically add rows by clicking a button. I found this article (https://www.geeksforgeeks.org/how-to-dynamically-add-remove-table-rows-using-jquery/) that uses jquery that works well great, even shows how to delete a line, whilst also renaming the <tr> tag id to the correct number as well as the text content of the first <td> tag.
However, I added an autocomplete input using materialize, and thought I could use the same method to change the <input> ID when deleting a row, but, seem to be failing miserably.
To see what I'm talking about, I'd invite you to run the code snippit, and add a few rows. If you delete any of the rows (apart from the last one), then all the Row numbers go down by one, the <tr> tag ids go down by one, but the <input> tag ids don't.
I apologize if my query isn't clear, and would be happy to try and explain more, if needed.
Here is all the code to recreate the project in a "normal" code editor :
JS in first snippit, html in second
let rowIdx = 1;
//This list would be generated from a google sheet on page load for the autocomplete input
let listRecettes = {
"Banana": null,
"Orange": null,
"Mango": null,
}
//ON LOAD
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems);
// Load words into autocomplete
populateWordsRecettes();
});
//Autocomplete initialize
function populateWordsRecettes() {
var autocomplete = document.getElementById("recettes1");
var instances = M.Autocomplete.init(autocomplete, {
data: listRecettes
});
}
//autocomplete initialize for added rows
function newLineAutocomplete() {
var autocomplete = document.getElementById(`recettes${rowIdx}`);
var instances = M.Autocomplete.init(autocomplete, {
data: listRecettes
});
console.log(`Row ${rowIdx} initialized`);
}
document.getElementById('btnAjouterLigne').addEventListener('click', addLine);
function addLine() {
// jQuery button click event to add a row.
// Adding a row inside the tbody.
$('#tableBodyCasse').append(`<tr id="R${++rowIdx}">
<td class = "row-index">Row ${rowIdx}</td>
<td><div class = "input-field"><input type="text" id="recettes${rowIdx}" class="autocomplete"></div></td>
<td>Lorum Ipsum</td>
<td>Lorum Ipsum</td>
<td>Lorum Ipsum</td>
<td><button class="btn waves-effect red darken-4 waves-light btnSupprimerLigne">Delete</button></td>
</tr>`);
//Initialize the autocomplete for new row
newLineAutocomplete();
}
//delete line
$('#tableBodyCasse').on('click', '.btnSupprimerLigne', function() {
// Getting all the rows next to the
// row containing the clicked button
let child = $(this).closest('tr').nextAll();
// Iterating across all the rows
// obtained to change the index
child.each(function() {
// Getting <tr> id.
let id = $(this).attr('id');
// Getting the <p> inside the .row-index class.
let idx = $(this).children('.row-index');
// Gets the row number from <tr> id.
let dig = parseInt(id.substring(1));
// Modifying row index.
idx.html(`Row ${dig - 1}`);
// Modifying row id.
$(this).attr('id', `R${dig - 1}`);
});
//MY PROBLEM STARTS HERE
let childInput = $(this).find('input').nextAll();
childInput.each(function() {
let idInput = $(this).attr('id');
let digInput = parseInt(idInput.substring(9));
console.log(digInput);
$(this).attr('id', `recettes${digInput - 1}`);
});
// Removing the current row.
$(this).closest('tr').remove();
// Decreasing the total number of rows by 1.
rowIdx--;
});
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<div class="container">
<!-- CONTAINER START -->
<table class="striped">
<thead>
<tr>
<th>Row num</th>
<th>Product</th>
<th>Type</th>
<th>Qty</th>
<th>Total</th>
<th>Delete line</th>
</tr>
</thead>
<tbody id="tableBodyCasse">
<tr id="R1">
<td class="row-index">Row 1</td>
<td>
<div class="input-field"><input type="text" id="recettes1" class="autocomplete"></div>
</td>
<td>unknown</td>
<td>2</td>
<td>5,4</td>
<td><button class="btn waves-effect red darken-4 waves-light btnSupprimerLigne">Delete</button>
</td>
</tr>
</tbody>
</table>
<button class="btn waves-effect waves-light" id="btnAjouterLigne">Add line
<i class="material-icons left">add_circle_outline</i>
</button>
</div>
<!--CONTAINER END -->
<?!= include("page-casse-js"); ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

jquery datatable edit table row data using form

var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
tb.row.add([typeName, amount]).draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
</tr>
</thead>
</table>
i need to append edit and delete button for every row. when click the edit button, row data should load to dropdown and textbox. can u guide me to do this ?
With certain changes to the architecture of your app, I would suggest the following approach that employs native DataTables options and API methods:
//initialize DataTable
const tb = $('#example').DataTable({
//remove non-essential controls for the sake of cleaner view
dom: 't',
//use columns option to setup header titles
columns: [
{title: 'Type'},
{
title: 'Amount',
//user 'render' to append Edit/Delete buttons for each entry
render: data => `${data}<button action="delete">Delete</button><button action="edit">Edit</button>`
}
]
});
//click handler for dual purpose 'Submit' button that adds new rows and submits edits
$('#submit').on('click', function() {
//when submit button acts to append new row to the table (default)
if($(this).attr('action') == 'addRow'){
tb.row.add([$("#type").val(), $("#amount").val()]).draw();
}
//when submit button acts to submit edits
if($(this).attr('action') == 'confirmEdit'){
//change affected row data and re-draw the table
tb.row($(this).attr('rowindex')).data([$("#type").val(), $("#amount").val()]).draw();
}
//clean up form, switch it to default state
$('#type').val("");
$('#amount').val("");
$('#submit').attr('action', 'addRow');
});
//'Delete' button click handler
$('#example').on('click', 'tbody tr button[action="delete"]', function(event){
tb.row($(event.target).closest('tr')).remove().draw();
});
//'Edit' button click handler
$('#example').on('click', 'tbody tr button[action="edit"]', function(){
//get affected row entry
const row = tb.row($(event.target).closest('tr'));
//get affected row().index() and append that to 'Submit' button attributes
//you may use global variable for that purpose if you prefer
$('#submit').attr('rowindex', row.index());
//switch 'Submit' button role to 'confirmEdit'
$('#submit').attr('action', 'confirmEdit');
//set up 'Type' and 'Amount' values according to the selected entry
$('#type').val(row.data()[0]);
$('#amount').val(row.data()[1]);
});
tbody tr button {
display: block;
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<label>Type</label>
<select id="type">
<option value="" selected></option>
<option value="Type 01">Type 01</option>
<option value="Type 02">Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="submit" action="addRow">Submit</button>
<table id="example" class="display" cellspacing="0" width="100%"></table>
Add your HTML directly. I've added button, you can similarly add a drop down too. Consider the following:
var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
var row = tb.row.add([typeName, amount, "<span><button>Edit</button><button>Delete</button></span>"]).draw();
var edit = row.node().getElementsByTagName("button")[0];
edit.onclick = function() {
document.getElementById('typeEdit').value = row.data()[0];
document.getElementById('amtEdit').value = row.data()[1];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<br/ >
<br/ >
Edit Type
<select id="typeEdit">
<option> Type 01</option>
<option> Type 02</option>
</select>
Edit Amount
<input id="amtEdit" />
<br/ >
<br/ >
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
<th>Ops</th>
</tr>
</thead>
</table>
RowEditor.js
I had a similiar issue and wrote a tiny JS tool, that targets editing of rows inline. The repo can be found here. I think its functionality is best described by the picture below, but you can also find a running example here.
Setting it up
What you have to do to integrate it, is
Download and integrate the file
<script type="text/javascript" charset="utf8" src="/js/RowEditor.js"></script>
Set up a configuration about which columns shall be editable and if they should be editable as dropdown or input (compare it to the example picture, you will quickly figure out what it does):
"1":{"type":"input"},
"2":{"type":"input"},
"3":{"type":"select",
"options":{
"1":{"value":'Sales Assistant', "title":'Sales Assistant'},
"2":{"value":'Tech Lead', "title":'Tech Lead'},
"3":{"value":'Secretary', "title":'Secretary'},
"4":{"value":'Developer', "title":'Developer'},
"5":{"value":'Trainee', "title":'Trainee'}
}
}
}
Call the editor, after you have initialized your DataTable:
$(document).ready( function () {
table = $('#table').DataTable();
rowEditor = new RowEditor('#table', table, editRowSettings);
});
Call the function editRow of rowEditor (or however you have named it above) with the index of the row you want to edit. I have the button placed in a sepperate column of the datatable, but you can call it anyway you want it.
<button onclick="rowEditor.editRow(1)">Edit</button>
If you have questions, feel free to ask or issue a pull request :)

Add rows to a html table from a textbox value

I want to copy the first row into the same table as many times as you type in, in a textbox.
<table id='table1'>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr id="row">
<td>1</td><td>2</td><td>3</td>
</tr>
<table>
<input id="Button1" type="button" value="button" onclick="showRow()"/>
<input id="Text1" type="text" />
<script>
function showRow() {
var header = Array();
$("#row").each(function (i) {
header[i] = $(this).text();
})
alert(header);
}
</script>
So I have created an array of the first row that alerts when you click the button.
An example of my question:
If i type 5 in the textbox and click on the button the table should look like this:
ABC
123
123
123
123
123
Is this possible?
I've made the class row rather than the id, so that we can target it (clone() would prevent duplicate ids anyway.)
You can just store the row as a jQuery object and then use a for() loop to clone that object and append it. Use the value entered in the textbox within your loop:
var $tbl = $('#table1'), origRow = $tbl.find('.row').first();
$('#Button1').on('click', function(){
var num = $('#Text1').val();
$tbl.find('.row').remove();
for(i=0; i<num; i++){
var newRow = origRow.clone();
$tbl.append(newRow);
}
});
JSFiddle
I wasn't sure whether you would want the table to empty each time or just add the rows on to the end. If you want the rows to be added to the end, just remove the $tbl.find('.row').remove(); line.
Try thisLink
<table id='table1'>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr class="row">
<td>1</td><td>2</td><td>3</td>
</tr>
<table>
<input id="Button1" type="button" value="button" onclick="showRow()"/>
<input id="Text1" type="number" />
$(document).ready(function () {
$('#Button1').click(function(){
var num = $('input[id="Text1"]').val();
alert(num);
for(var i=0;i<num;i++){
$('table[id="table1"]').append(' <tr class="row"><td>1</td><td>2</td><td>3</td></tr>');
}
});
});
Ofc it is, just parse the textbox val() or value as int and to a for() loop to that number
Using jquery there is a lot of ways to do it. Look at these jQuery functions :
clone()
appendTo()
insertAfter()
You can try this one:
Logic is simple: Get the count from textbox, create row count no of times and append that row after last row in table. $('#row').html() will give inner element of first row.
<script>
function showRow() {
var i, num = $('#Text1').val();
for(i=0; i<num; i++){
$('#table1 > tbody:last').append('<tr id=row'+i+1+'>'+$('#row').html()+'</tr>');
}
}
</script>
DEMO Link
LIVE DEMO
Try this:
Change your row to class.
HTML:
<table id='table1'>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr class="row">
<td>1</td><td>2</td><td>3</td>
</tr>
<table>
<input id="Button1" type="button" value="button" />
<input id="Text1" type="text" />
JQUERY:
$('#Button1').on('click',function(e) {
limit = $("#Text1").val();
for(i=0;i<parseInt(limit);i++) {
strText = $(".row").first().clone();
strText.appendTo("#table1");
}
});

"Add Row" logic not working as expected

It has taken me days to come up with the following, and now I'm realizing that it still doesn't work. My "add row" button isn't working properly. What am I missing?
<table>
<tr>
<th>field</th>
<th>comparison</th>
<th>value</th>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
<td><button id="add">Add row</button></td>
</tr>
</table>
$('#tableSearchMainAccount1 tr').each(function() {
var td = '';
// used to skip table header (if there is)
if ($(this).find("td:first").length > 0) {
$(this).find('option:selected').each(function() {
td = td + $(this).text() + ',';
});
td = td + $(this).find('input').val();
filt[ctr] = td;
ctr += 1;
}
});
//alert(filt); //alert output like name,equals,ann,age,equals,11
$('#add').live('click', function() {
var $lastTr = $('table tr:last');
console.log($lastTr);
$lastTr.clone().insertAfter($lastTr);
// Remove the button from the previous tr, otherwise each row will have it.
$('#add', $lastTr)
.replaceWith('<button class="remove_row">Remove row</button>');
});
$('.remove_row').live('click', function() {
$(this).closest('tr').remove();
});
From the discussion in the comments, it appears you have not referenced jQuery.
Add the following to your <head></head> section:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
There are many other CDNs that host jQuery for you, or you can download it yourself. All of these details can be found on http://jquery.com/download/.
So that your markup looks something like the following:
<!DOCTYPE html>
<html>
<head>
<title>My jQuery Project</title>
<script src="jquery-1.8.3.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<table>...</table>
</body>
</html>
Note that I also referenced another external file called "scripts.js". This is where you could place all of your JavaScript and jQuery logic.
$(document).ready(function(){
/* Wrapping your code with a document-ready
block will ensure that the DOM will be
ready before your code runs
*/
});
replace
<table>
with
<table id="tableSearchMainAccount1">
would be my starter for 10.

Categories

Resources