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);
};
});
});
1.This is my code for my HTML table where I'm unable to display the data from it using my javascript code below.
<table id="empTable">
<tr>
<th>Type</th>
<th>SimiScore</th>
<th>Rank</th>
<th>Introversion/Extraversion</th>
<th>Intuitive/Observant</th>
<th>Thinking/Feeling</th>
<th>Judging/Perceiving</th>
</tr>
{% for doc in docs %}
<tr>
<td>{{doc["type"]}}</td>
<td>{{doc["Simiscore"]}}</td>
<td>{{doc["Rank"]}}</td>
<td>{{doc["Introversion/Extraversion"]}}</td>
<td>{{doc["Intuitive/Observant"]}}</td>
<td>{{doc["Thinking/Feeling"]}}</td>
<td>{{doc["Judging/Perceiving"]}}</td>
</tr>
{% endfor %}
</table>
<p><input type="button" id="bt" value="Show Table Data" onclick="showTableData()" /></p>
<p id="info"></p>
2.This is my javascript code to display the data, but I'm unable to display it
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + '<br />'; // ADD A BREAK (TAG).
}
}
</script>
{
$(document).ready(function()
{
$.ajax({
url: "getjson.php",
type: "POST",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
$('#records_table').append(trHTML);
}
});
});
}
this is an example you can use
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 get an ajax call response in which i get datetime in "2019-02-07T14:00:11.374+0530" format. I want to convert this as Feb-07-2019 14:00.
I try this as following but its showing current date, not ajax response date. How do i convert date coming from ajax response. I get datetime from ajax response by calling "starttime"
This my code
function format(driver_data) {
var a = '';
var b = '';
var i;
var ps = new Date();
ps = ps.toDateString() + " " + ps.getHours() + ":" + ps.getMinutes();
console.log(ps)
for (i = 0; i < driver_data.length; i++) {
a = '<table class="table table-striped table-bordered table-hover"style="padding-left:0px;">' + '<thead> <tr> <th>Trip Id</th> <th>Name</th> <th>Source</th> <th>Destination</th> <th>Date/Time</th> </tr> </thead>' + '<tbody>';
b = b + '<tr>' +
'<td>' + driver_data[i].d_tripid + '</td>' +
'<td>' + driver_data[i].employeename + '</td>' +
'<td>' + driver_data[i].srclocation + '</td>' +
'<td>' + driver_data[i].destlocation + '</td>' +
'<td>' ps'</td>' +
'</tr>';
}
var final = a + b + '</tbody></table>';
return final;
}
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