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);
};
});
});
Related
I've made the following dynamic table, which rows are created for each record found in database.
$(document).ready(function () {
var $form = $('#my-form');
$form.submit(function () {
$.post($(this).attr('action'), $(this).serialize(), function (response) {
let table = '<table> <thead> <tr> <th>Candidate Name</th> <th>Candidate Surname</th> <th>Interview Type</th> <th>Interview Date</th> <th>Interviewer</th> <th>Feedback</th> </tr> </thead><tbody>';
response.forEach(function (d) {
table += '<tr><td>' + d.candidateName + '</td>';
table += '<td>' + d.candidateSurname + '</td>';
if (d.interviewType === 1) {
table += '<td>MOTIVAZIONALE</td>';
} else if (d.interviewType === 2) {
table += '<td>TECNICO</td>';
} else {
table += '<td></td>';
}
if (d.scheduledDate === null) {
table += '<td></td>';
} else {
table += '<td>' + d.scheduledDate + '</td>';
}
table += '<td>' + d.enterpriseId + '</td>';
if (d.finalFeedback === null) {
table += '<td><button type="button" onclick="sendValue(d.idColloquio)">Add a feedback</button></td></tr>';
}else{
table+= '<td>OK</td></tr>';
}
})
table += '</tbody>';
$('#mytable').empty().html(table);
}, 'json');
return false;
});
});
In each row there is a button used to insert a feedback: this button have to redirect in another page by passing the id as a request parameter, but the "onClick" function doesn't work. On Chrome inspector event in generated.
SendValue:
function sendValue(id) {
window.location.href="insertMotivationFeedback?idColloquio="+id;
}
Anyone can help me?
Thanks
You have to pass complete url:
window.location.href="https://example.com/insertMotivationFeedback?idColloquio="+id;
I am working with chrome extension .My main problem is I am not
able to append my tr under tbody as the error occur and stating
"Cannot read property 'getElementsByTagName' of null". So how Do I
append this in chrome extension using javascript.
In background.js I have tried this:
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
I am hitting API and and my response is under data.
When I console my result so as output tr is comming.
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var tableRef = document.getElementsByTagName('tbody')[0];
both lines are giving this "Cannot read property 'getElementsByTagName' error
I also tried other ways to append but everytime it gives same error.I am not getting why this is happening.
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
```
```background.html```
<div class="table-responsive mb-0" data-toggle="lists">
<table class="table table-sm table-nowrap card-table" id="myTable">
<thead>
<tr>
<th>Product Name</th>
<th>Category</th>
<th>Price</th>
<th>Favourites</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
```
<script src="background.js"></script>
> I am getting error "Cannot read property 'getElementsByTagName' of null". I only want to append my tr under tbody
I think that your background.js executes before the page has loaded, You can't access the "tbody"
This is how to run background.js after page load.
<script>
function init(){
var tag = document.createElement("script");
tag.src = "background.js";
document.getElementsByTagName("head")[0].appendChild(tag);
}
</script>
<head></head>
<body onload='init()'>
<table><tbody><tbody></table>
</body>
I have a firebase database set up that I need to create an HTML table with that necessary info. Below is how I have set up my firebase data.
{
"Markets" : {
"Athens" : {
"Item" : {
"name" : "Beef",
"price" : 10,
"salePrice" : 3
}
}
}
}
This is how I have my HTML table set up and my code to attempt to retrieve the data. The table is appropriately being created but I am not seeing any data. Any help would be greatly appreciated.
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Name:</th>
<th>Price:</th>
<th>Sale Price:</th>
</table>
<script>
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.price + '</td>';
content += '<td>' + val.salePrice + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
Right now you're reading the root node. There are a few more levels of data in your JSON before you get to the name, price and salesPrice properties. You'll either need to navigate those levels in your callback, or in your query. An example of the latter:
var database = firebase.database();
database.ref('Markets/Athens').once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.price + '</td>';
content += '<td>' + val.salePrice + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
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 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