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
Related
I have an Html table and I'm feeding that table with data from firebase so in my Html there's no table data td i have tried to add on click on the table row tr but this is adding the click on the table header th
<div>
<table>
<tr onclick="myFunction(this)">
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tbody id="table">
</tbody>
</table>
</div>
<script>
function myFunction(x) {
alert("Row index is: " + x.rowIndex);
}
</script>
the second try is js I have tried this and many other functions like this one but it did nothing no response no errors
function addRowHandlers() {
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
and this is how im feeding td from firebase
var ref = firebase.database().ref("users");
ref.on("value", function(data){
$('#table').empty()
var content = '';
data.forEach(function(childSnapshot){
if (childSnapshot.exists()){
var childData = childSnapshot.val();
console.log(childData);
content +='<tr>';
content += '<td>' + childData.username + '</td>';
content += '<td>' + childData.phone + '</td>';
content += '<td>' + childSnapshot.key + '</td>';
content += '</tr>';
};
});
$('#table').append(content);
});
how to add onClick event to each row I'm new to HTML and js languages
You can refactor your function like
var ref = firebase.database().ref("users");
ref.on("value", function (data) {
$('#table').empty()
data.forEach(function (childSnapshot) {
if (childSnapshot.exists()) {
var childData = childSnapshot.val();
console.log(childData);
const tr = document.createElement('tr')
let content = ""
content += '<td>' + childData.username + '</td>';
content += '<td>' + childData.phone + '</td>';
content += '<td>' + childSnapshot.key + '</td>';
tr.innerHTML = content;
tr.onclick = function () {
alert('tr', childData.phone)
}
$('#table tbody').append(tr);
};
});
});
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>
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.
For example : I want to insert many tr in a table like this
var tbody = $('#tbody')
// Suppose the articlelist is the data from ajax
while (articlelist.length > 0) {
var article = articlelist.shift(),
var tr = $(' <tr>'
+' <td>'+article.id+'</td>'
+'<td>' + article.channelid +'</td>'
+ '<td>'+article.comment+'</td>'
+'<td>'+article.last_edit_time+'</td><td>'
)
tbody.append(tr)
}
To avoid create the <tr>...</tr> in loop .Is it possible to use a class to generate the tr content ?
An optimized version:
var tbody = $('#tbody'),
htmlStr = "";
for (var i = 0, len = articlelist.length; i < len; i++) { // avoid accessing 'length' property on each iteration
htmlStr += '<tr><td>' + articlelist[i].id + '</td>'
+ '<td>' + articlelist[i].channelid + '</td>'
+ '<td>' + articlelist[i].comment + '</td>'
+ '<td>' + articlelist[i].last_edit_time + '</td><td><tr>';
}
tbody.append(htmlStr); // parses the specified text as HTML or XML and inserts the resulting nodes
You could use a loop to concatenate all the strings, then append this lengthy string all at once. This would help with performance for many trs
var tbody = $('#tbody')
var rows = ''
while (articlelist.length > 0) {
var article = articlelist.shift(),
rows += '<tr><td>'+article.id+'</td>'
+'<td>' + article.channelid +'</td>'
+ '<td>'+article.comment+'</td>'
+'<td>'+article.last_edit_time+'</td><tr>';
}
tbody.append(rows)
add a function like this to do this for you.
while (articlelist.length > 0) {
make_content(article);
}
function make_content(article) {
var tbody = $('#tbody');
var tr = $(' <tr>'
+' <td>'+article.id+'</td>'
+'<td>' + article.channelid +'</td>'
+ '<td>'+article.comment+'</td>'
+'<td>'+article.last_edit_time+'</td><td>'
)
tbody.append(tr)
}
I want to build an HTML table string for every 10 items in a Javascript array, and if there are less than 10 items in the last iteration I want to fill it with empty rows.
How do I achieve this?
var array_of_items; //array of items
//make a html table string every 10 items
var table = '<table>';
table += '<tr><td>' + item1 + '</td></tr>';
table += '<tr><td>' + item2 + '</td></tr>';
.
.
.
table += '<tr><td>' + item10 + '</td></tr>';
table += '</table>';
//make second table
table = '<table>';
table += '<tr><td>' + item11 + '</td></tr>';
table += '<tr><td>' + item12 + '</td></tr>'; //array ends here
table += '<tr><td></td></tr>';
.
.
.
table += '<tr><td></td></tr>';
table += '</table>';
$('#table_div').html(table);
var table = '';
var numTables = Math.ceil(array_of_items.length / 10); //determine how many tables
for (var i=0;i<numTables;i++){
table +='<table>';
for (var j=0;j<10;j++){
(array_of_items[i*10+j] ? table +='<tr><td>' + array_of_items[i*10+j] + '</td></tr>' : table +='<tr><td></td></tr>');
}
table +='</table>';
}
var ln = items.length;
var lnten = ln + 10 - ln%10;
var container = $('#table_div');
for (var j = 0; j < lnten; j++) {
var tbl;
if (j % 10 == 0)
tbl = $('<table/>');
var tr = $('<tr/>');
var td = $('<td/>');
if (j < ln)
td.text(items[j]);
tr.append(td);
tbl.append(tr);
if (j % 10 == 0)
container.append(tbl);
}
jsfiddle DEMO
I think you're looking for this
for (var i = 0; i < array_of_items.length; i+=10) {
var table = '<table>';
for (var j = i; j < i+10; ++j) {
if (array_of_items[j] === 'undefined') {
table += '<tr><td></td></tr>';
}
else table += '<tr><td>' + array_of_items[j] + '</td></tr>';
}
table += '</table>';
}