Append button to a table row dynamically using jquery - javascript

I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.
jQuery Code:
$.each(objArr, function(key, value) {
var tr = $("<tr />");
$.each(value, function(k, v) {
tr.append($("<td />", {
html: v
}));
$("#dataTable").append(tr);
})
})
The code works perfectly and the table is getting populated successfully
But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action
I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:
for (var i = 0; i < objArr.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + objArr[i]["empID"] + "</td>";
var td2 = "<td>" + objArr[i]["fname"] + "</td>";
var td3 = "<td>" + objArr[i]["lname"] + "</td>";
var td4 = "<td>" + objArr[i]["phone"] + "</td>";
var td5 = "<td>" + objArr[i]["address"] + "</td>";
var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
var td7 = "<td>" + objArr[i]["email"] + "</td>";
var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
')">Delete</button>' + "</td></tr>";
$("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}
Any suggestions please?

Try something like this:
$.each(objArr, function (key, value) {
var tr = $("<tr />");
$.each(value, function (k, v) {
tr.append($("<td />", { html: v }));
tr.append("<button class='remove' />");
$("#dataTable").append(tr);
})
})
This shall append the button at the end of the tr with class remove.

Try this, I've include event handler for the each buttons inside the table.
CHANGES:
Adding Event Listener for each buttons inside the table.
Call method (function) with parameters.
Note:
I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.
EXPLAINS :
var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
JQUERY REFFERENCES :
.parents()
:nth-child()
$(this) OR $(this)
$(document).ready(function() {
var jsonData = [
{id: 'A01', name: 'Fadhly'},
{id: 'A02', name: 'Permata'},
{id: 'A03', name: 'Haura'},
{id: 'A04', name: 'Aira'}
];
$.each(jsonData, function(key, val) {
var tr = '<tr>';
tr += '<td>' + (key + 1) + '</td>';
tr += '<td>' + val.id + '</td>';
tr += '<td>' + val.name + '</td>';
tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
tr += '</tr>';
$('tbody').append(tr);
});
$('button.delete').on('click', function() {
var cRow = $(this).parents('tr');
var cId = $('td:nth-child(2)', cRow).text();
var intKey = $(this).data('key');
cRow.fadeOut('slow', function() {
doDelete(cId, intKey);
});
});
function doDelete(param1, param2) {
alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<tr>
<th>#</th>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Related

Get table row value with jQuery/JS

I am trying to get table value names with the following code:
my table :
function CreateBlockDeployTableRow(data) {
return "<tr>" +
"<td>" + data.EnvTypeName + "</td>" +
"<td>" + data.AppTypeName + "</td>" +
"<td>" + deleteBtn + "</td>" +
"</tr>";
}
my button:
var deleteBtn = '<button class="btn btn-danger unblock-button btn-sm
glyphicon glyphicon-minus" type=button > </button> '
on click function:
function UnblockRequestHandler()
{
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler();
});
}
and here I want to send my Environment and Application to server side and take the value of the rows in the table , but the code is not working and not taking anything:
function sendUnblockDeploySubmitHandler() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML +
'<br/>';
alert(values);
});
console.log(values);
}
html code :
<div class="tbl-responsive">
<table id="blockDeployTable" class="table table-hover
requestsblockDeployTable" style="font-size: 0.8em; margin-top: 120px;
text-align:center">
<thead>
<tr>
<th>Environment</th>
<th>Repo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Where am I wrong here I cannot understand?
You could just pass the click event through to the sendUnblockDeploySubmitHandler function:
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler(event); // pass event to function
});
function sendUnblockDeploySubmitHandler(event) {
var $row = $(event.target).closest('tr'); // event.target is the button
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
}
I've put together a jsbin to show this working: https://jsbin.com/sosimudubi/1/edit?html,js,console,output
You are trying to access jQuery(this) in the sendUnblockDeploySubmitHandler() method but the this handle does not refer to the button element. I would suggest you to directly pass the callback function when you bind the click event.
function UnblockRequestHandler() {
$('.unblock-button').click(sendUnblockDeploySubmitHandler);
}
This way, you can access the corresponding button element using jQuery(this) in the sendUnblockDeploySubmitHandler()

How to get the Dynamic Table cell value on button click

I've a table which is dynamically generated. In its row, I'm placing buttons.
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test()'></td>";
tr = tr + "</tr>";
};
On a button click, I'd like to get the particular cell value of that row. E.g.: If I click on the age in the first row, then the value I have to get is 50. And if I click on the button in second row, then I should get 94.
How can I get the table cell value on a button click?
Here is your solution for dynamic table:
<script language="javascript">
var tbl = document.getElementById("tblId");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
</script>
So, By using this javascript you can get value of any table cell.
You can pass age to button onclick function like onclick='test('"+resp[i].age +"')'
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test("+resp[i].age +")'></td>";
tr = tr + "</tr>";
};
Here is your solution:
$(document).find('.theButton').on('click',function(){
var age = $(this).parents('tr:first').find('td:eq(1)').text();
console.log(age);
});
Try this example with jQuery, I have replaced your function test, with rowid
https://jsfiddle.net/ucostea/2thyj0ft/
$(document).on("click", ".theButton", function(){
alert("Aage: "+$('.age_'+$(this).attr('rownr')+'').text());
});
for (var i = 0; i < 10; i++) {
var tr = "";
tr = tr + "<tr >";
tr = tr + "<td class='date_"+i+"'>Date" + i + "</td>";
tr = tr + "<td class='age_"+i+"'>Age " + i + "</td>";
tr = tr + "<td class='hour_"+i+"'>Hour " + i + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' rownr='" + i + "'></td>";
tr = tr + "</tr>";
$('.table tbody').append(tr);
};

How to make HTML table from JSON objects data

I am trying to create an HTML table from JSON objects data with a for loop in a function. Below is the key part of my code that is clearly not working as intended and I am struggling to figure it out.
var table = ''
var forLoopData = function() {
for (j=0; j<dataJson.length; j++) {
table += '<tr';
for(var i=0; i<6; i++) {
table += "<td>" dataJson[i].id "</td>" "<td>"dataJson[i].firstName"</td>" "<td>"dataJson[i].lastName"</td>" "<td>"dataJson[i].dateOfBirth"</td>" "<td>"dataJson[i].function"</td>" "<td>"dataJson[i].experience"</td>";
}
table += </tr>
}
};
forLoopData();
document.write('<table>' + table + '</table>');
Your table lacks the table, tbody and tr tags.
<table>
<tbody>
<tr>
<td>dataJson[i].id</td>
<td>dataJson[i].firstName</td>
<td>dataJson[i].lastName</td>
</tr>
</tbody>
</table>
This is what you need to build.
Here is how:
var table = "<table><tbody>";
for(var i=0; i<6; i++) {
table += "<tr>" ;
table += "<td>" + dataJson[i].id "</td>" ;
table += "<td>" + dataJson[i].firstName + "</td>" ;
table += "<td>" + dataJson[i].lastName + "</td>" ;
table += "</tr>" ;
}
table += "</tbody></table>";
with your table ready you can use document.write(table)
Thank you everyone for trying to help me. Unfortunately I dropped this idea and did not have the chance to test your answers. Combining vanilla JavaScript with html elements is still hard for me and I decided to go with bootstrap framework. Below is code I used:
$.getJSON("data.json", function(data){
var items = [];
$.each(data, function(key, val){
items.push("<tr>");
items.push("<td id =''"+key+"''>"+val.id+"</td>");
items.push("<td id =''"+key+"''>"+val.firstName+"</td>");
items.push("<td id =''"+key+"''>"+val.lastName+"</td>");
items.push("<td id =''"+key+"''>"+val.dateOfBirth+"</td>");
items.push("<td id =''"+key+"''>"+val.function+"</td>");
items.push("<td id =''"+key+"''>"+val.experience+"</td>");
items.push("</tr>");
});
$("<tbody/>", {html: items.join("")}).appendTo("table");
});

Is it possible to iterate through each item in an array and output as HTML?

I have a for loop that pushes targeted properties into an array if they pass a certain condition. I would like to create a table that outputs each item into its own row. The tricky part for myself is understanding how this can be done dynamically. It's easy to hardcode each item from the array and insert it into a row. But can this be done automatically using pure JS?
script.js
var myArray = [];
for (var i = 0; i < ccirdata.length; i++) {
if (ccirdata[i].catType === 'I') {
myArray.push(ccirdata[i].catNum);
}
};
In the same file,
I have the outline for my table where I'm trying to insert the iterations from 'myArray':
var header =
"<thead>" +
"<tr>" +
"<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +
"<td class='key'>" + " My Table:</td>" +
"</tr>" +
"</thead>";
var rows =
"<tr>" +
"<td class='key'><strong>" + <INSERT HERE> + "</strong></td>" +
"</tr>"
return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>";
How can I create a new row dynamically for each item in myArray?
Here's one approach:
// using the same header code you provided
var rows = "";
myArray.forEach(function(item, index) {
rows += "<tr>";
rows += "<td class='key'><strong>" + item + "</strong></td>";
rows += "</tr>";
});
return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>";
You can loop through myArray to create each row and concatenate them into a larger string.
var rows = "";
for (var r = 0; r < myArray.length; r++) {
var row = "<tr>" + "<td class='key'><strong>" + myArray[r] + "</strong></td></tr>";
rows = rows.concat(row);
}
Instead of building a text string to later set as HTML, I would opt for using a cleaner approach with insertRow like this:
<table>
<thead>
<tr><td>A header</td></tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var values = ['foo', 'bar', 'baz']; // Values to insert in table
// Get a reference to the <tbody> element
var tbody = document.querySelector('tbody');
for (var i = 0; i < values.length; i++) {
// This appends a new row to the <tbody> and returns a reference
// to that element
var row = tbody.insertRow();
// Similarly to append a cell to the row
var cell = row.insertCell();
// Create a text node for the textual content and append it
// to the cell
var text = document.createTextNode(values[i]);
cell.appendChild(text);
}
</script>
As demonstrated in this JSFiddle.

JS Append Row in HTML Table

I have a hidden field with some values, I have to append these values in HTML table.The number of columns in table is fixed.
I have appended successfully,but after first row,it should append data in new row,instead it is appending in the same row.
This is how I am doing
$("#btntbl").click(function () {
debugger
var tabl = $("#testTable");
var vals = $("#txthidden").val();
for (var i = 0; i < vals.split(";").length; i++) {
for (var j = 0; j < vals.split(";")[i].split(",").length; j++) {
tabl.append("<td>" + vals.split(";")[i].split(",")[j] + "</td>");
}
}
});
Also note that some users dont have value of disabled column
JS Fiddle
How can I add new row each time clicking the button?
You need to split twice and create tr for each row:
$("#btntbl").click(function () {
var tabl = $("#testTable"),
vals = $("#txthidden").val(),
rows = vals.split(';'),
columns, i;
for (i = 0; i < rows.length; i++) {
columns = rows[i].split(',');
tabl.append(
'<tr>' +
'<td>' + columns[0] + '</td>' +
'<td>' + columns[1] + '</td>' +
'<td>' + (columns[2] || '') + '</td>' +
'</tr>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btntbl" value="Export to table">
<input type="hidden" value="User1,pwd1;User2,pwd2,disabled;User3,pwd3,disabled;User4,pwd4" id="txthidden" />
<table id="testTable" border="2">
<thead valign="top">
<tr>
<th>User</th>
<th>Password</th>
<th>Disabled</th>
</tr>
</thead>
</table>
Just change target by adding a row
Change
var tabl = $("#testTable");
To
var tabl = $('<tr>');
$("#testTable").append( tab1);
Here is how you can do it
var convertToTable = function (val) {
val = val.split(';');
val = val.map(function (v) {
v = v.split(',');
if (v.length === 2) v[v.length] = 'NA';
return '<td>' + v.join('</td><td>') + '</td>';
});
val = '<tr>' + val.join('</tr><tr>') + '</tr>';
return val;
}
and then
tabl.html(convertToTable(vals));
Demo here
jsFiddle demo
$("#btntbl").click(function () {
var parts = $("#txthidden").val().split(";"), i=0;
for (;i<parts.length;) {
var j=0, tr="<tr>", subParts=parts[i++].split(",");
for (;j<3;) tr += "<td>" + (subParts[j++]||"") +"</td>"; // concatenate
$("#testTable").append( tr +"</tr>" ); // Append once
}
});
You forgot about TD tag, just use open tag before TD and close it in the end

Categories