In this JSFiddle demo, i tried to add a row dynamically only knowing the id of one of the previous element of the table. The code works perfectly, otherwise i want to beautify it. In particular i wish to highlight the new inserted row, using this property:
.effect("highlight", color: '#4BADF5'}, 1000);
Any suggestions?
Thanks
First of all - you need to add the jQuery UI lib.
Second - your algorithm is not optimal one.
Please find an optimal solution below:
var myClick = function() {
var nome = "Hello";
var rowId = "120"
var row = "<tr><td>" + nome + "</td></tr>";
var newTr = $(".mytable1 tr #" + rowId).parent().after(row);
newTr.next().effect("highlight", { }, 2000);
};
$('#button').click(myClick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<input type="button" id="button" value="Add"/>
<table class="mytable1">
<tr><td id="12">1.0</td></tr>
<tr><td id="20">1.1</td></tr>
<tr><td id="120">1.2</td></tr>
<tr><td id="260">1.3</td></tr>
<tr><td id="2">1.4</td></tr>
<tr><td id="100">1.5</td></tr>
<tr><td id="23">1.6</td></tr>
</table>
Related
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>
First I create a table with n number of rows and each one of them contains a checkbox. I need to get all the ids from all the row checked.
<body>
<table border='1' style='width:100%'>
<tr id='1'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='2'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='3'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='4'><td>'hi'</td><td><input type='checkbox' /></td></tr>
</table>
<button id='test'>Get Checked</button>
</body>
This is what I got so far:
<script>
$(document).ready(function() {
$('#test').click(function(){
var getID = $(':checkbox:checked').closest('tr').attr('id');
alert(getID);
});
});
</script>
But this only gives me one id. If I select many rows I only get the first selected id. Also I need to store all the ids selected in an array for later use.
User jQuery's each function for this.
$(':checkbox:checked').each(function( index ) {
var closestTr = $(this).closest('tr').attr('id');
alert(closestTr);
});
In jQuery, use selector defaults to the first. so , we should use each get all selector element.
<script>
$(document).ready(function() {
$('#test').click(function(){
var arrId = [];
$(':checkbox:checked').each(function(){
var id = $(this).closest('tr').attr('id');
arrId.push(id);
})
console.log(arrId);
});
});
</script>
var getID = $(':checkbox:checked').closest('tr').attr('id');
Should be:
var getID = $('.checkbox:checked').closest('tr').attr('id');
Try something like this, demo in fiddle. Make sure adding open td , before each input checkbox
JS
$('#test').click(function(){
var ids = $(':checkbox:checked').map(function() {
var id = $(this).closest('tr').prop('id');
alert(id);
return id;
}).get();
alert(ids);
});
HTML
<table border='1' style='width:100%'>
<tr id='1'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='2'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='3'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='4'><td>'hi'</td><td><input type='checkbox' /></td></tr>
</table>
<button id='test'>Get Checked</button>
Put and id on your table:
<table id="myTab" border='1' style='width:100%'>
To avoid getting other checkboxes in the page, select the checkboxes from within the table like:
var ids = [];
$('#mytab :checkbox:checked').each(function( index ) {
var closestTr = $(this).closest('tr').attr('id');
ids.push(closestTr);
});
alert(ids);
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");
}
});
Just need your help.
My problem is I am creating a dynamic form. In my form there is a button and below that is a table.
The scenario is:
1. The user will click the the button
2. After clicking the button the table row will dynamically added. Inside my row there is a textbox
I can do that but how can i do the process after the user click the button. The row will append together with a textbox. But I want to assign a unique ID in a textbox. In my case I want to do this incremental.
Here's my js:
$(document).ready(function(){
$("[data-item]").on('click',function(){
$("#grid1 tbody").append("<tr><td><input type='text' value='123' style='width:100px' id='' /></td></tr>");
});
});
Here's my table:
<input type="button" name="add" data-item="123" value="ADD" class="test" id="test" />
<table id="grid1" border="1" style="width: 40%">
<thead>
<tr>
<th style="text-align: center;">CODE</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here's the fiddle:
http://jsfiddle.net/rochellecanale/xvdMz/
keep a counter
$(document).ready(function(){
var counter = 0;
$("[data-item]").on('click',function(){
$("#grid1 tbody").append("<tr><td><input type='text' value='123' style='width:100px' id='in-" + counter++ + "' /></td></tr>");
});
});
Demo: Fiddle
You can do it this way:
When you create a new row you can check for the current input's length and add that as a part of id.
$("[data-item]").on('click',function(){
var $el = $("<tr><td><input type='text' id='myInput" + ($('#grid1').find('input').length +1) + "' value='123' style='width:100px' id='' /></td></tr>");
$("#grid1 tbody").append($el);
});
Demo
I have another suggestion that instead of keeping the items to be cloned, you can go for templating, least you can put in your html itself like this.
<script type="text/html" id="clone">
<tr><td><input type='text' value='123' style='width:100px' id='' /></td></tr>
</script>
and then just use that to clone, this way you keep your html in one place and script in another.
$("[data-item]").on('click',function(){
var $el =$($.parseHTML($('#clone').html())).find('input').prop('id', "myInput" + ($('#grid1').find('input').length +1) ).end();
$("#grid1 tbody").append($el);
});
Demo
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.