I am trying to delete the contents of a upon click and repopulate it based on what they are clicking.
I was able to succesfully modify the with the new title, but I keep running into issues when I want to delete the contents of and replace it with a new one. I've tried doing the removeChild(), the replaceChild(), as well as innerHTML (which doesn't work based on documentation).
How would I successfully on a click, remove the existing table and repopulate it with HTML generated from JavaScript.
HTML:
<table id="captable" border = "5" width="100%" cellpadding="4" cellspacing="5">
<thead>
<tr>
<th colspan="100%">
<div id="table-title"></div>
</th>
</tr>
<th>Input Date</th>
<th>Requested Date</th>
</thead>
<tbody id="tbodyid">
<div id="table-entries">
<tr align = "center">
<td>3/27/2018</td>
<td>6/12/2018</td>
</tr>
</div>
</tbody>
</table>
JavaScript:
function(evt) {
$("#table-title").html("<h2><b>" + Title + ":</b><i> " + Subtitle + "</i></h2>");
var tBodyInner;
for (i of dataPoints) {
console.log("data" + i);
var data = json.Data[i];
tBodyInner += ("<tr align = \"center\">");
tBodyInner += ("<td><a target=\"_blank\" href=" + data.cap_url + ">" + data.capNumber + "</a></td>");
tBodyInner += ("</tr>");
}
//Not sure what to do here so that I clear the existing table, and appened the new tBodyInner html as a replacement
modal.style.display = "block";
}
First of all, you have to get rid of <div id="table-entries">, this is not a valid location for a DIV.
Second, you need to initialize the variable tBodyInner to an empty string.
Finally, you can use $("#tbodyId").html() to fill in the HTML of the table body.
function(evt) {
$("#table-title").html("<h2><b>" + Title + ":</b><i> " + Subtitle + "</i></h2>");
var tBodyInner = "";
for (i of dataPoints) {
console.log("data" + i);
var data = json.Data[i];
tBodyInner += ("<tr align = \"center\">");
tBodyInner += ("<td><a target=\"_blank\" href=" + data.cap_url + ">" + data.capNumber + "</a></td>");
tBodyInner += ("</tr>");
}
$("#tBodyId").html(tBodyInner);
modal.style.display = "block";
}
<table id="captable" border="5" width="100%" cellpadding="4" cellspacing="5">
<thead>
<tr>
<th colspan="100%">
<div id="table-title"></div>
</th>
</tr>
<th>Input Date</th>
<th>Requested Date</th>
</thead>
<tbody id="tbodyid">
<tr align="center">
<td>3/27/2018</td>
<td>6/12/2018</td>
</tr>
</tbody>
</table>
Where do you exactly change the html inside the element? You are setting the variable tBodyInner, but never using it. You should use it like you updated the title above, for example:
$("#table-entries").html(tBodyInner);
Also the parentheses around the string concats on the right side are redundant. No harm, but no effect either.
Related
First off - I did look at How to replace innerHTML of a div using jQuery? and that's great if I want to replace the fill tag <tr> in this case.
I'm trying to make a dynamic table that is loading off of an API for crypto-mining. Whenever there are new blocks hit, I want to add them to the top of the table and delete any over 100 (Only 100 <tr> max).
Right now, what I'm doing is:
document.getElementById('blockList').innerHTML += "<tr><td>" ...
This adds rows to the top of:
<table class="table1">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Time (Local)</th>
<th class='collapsableHeader' onclick='collapseTable()'>Hash</th>
<th>Height</th>
<th>Effort</th>
<th>Found By</th>
<th>Pool/Solo</th>
<th>Status</th>
</tr>
</thead>
<tbody id="blockList"></tbody>
</table>
The problem with the way I'm doing it now is that it clears the entire table:
document.getElementById("blockList").innerHTML = "";
...this causes a bit of flashing, or "twitching" as I prefer to call it, while the data reloads everytime my setInterval() is called (about every 10 seconds).
My first hope is that jQuery will minimize or remove the flashing. Here's where I get hung up - the link above is to replace the tag with new information with either:
$("#blockList").html("STUFF TO REPLACE EXISTING STUFF");
//or
$("#blockList").text("STUFF TO REPLACE EXISTING STUFF");
text() won't work in my case because I'm using the innerHTML += to add the tags as well...
document.getElementById('blockList').innerHTML += "<tr><td>" + i + "</td><td>" + displayBlocks[i]["timestamp"] + "</td><td class='collapsable'>" + displayBlocks[i]["hash"] + "</td><td class='collapsablePlaceholders'>|</td><td>" + displayBlocks[i]["height"] + "</td><td style='color:" + displayBlocks[i]["luckColor"] + "'>" + displayBlocks[i]["luck"] + "</td><td>" + displayBlocks[i]["worker"] + "</td><td>" + displayBlocks[i]["ps"] + "</td><td>" + displayBlocks[i]["status"] + "</td></tr>";
If this is possible, then removing the rows > 100 will be easy (I hope).
So - all this to say:
Is it possible to ADD information to an id/tag in jQuery without deleting all of the existing data in it. Basically the equivalent to .innerHTML += specifically the += part.
Here's some examples on how to add to top, add to bottom, remove from top and remove from bottom using JQ
let n = 0
$('button').click(function() {
n++
let fakerow = `<tr><td>${n}</td><td>12:34</td><td>123123123</td><td>10</td><td>??</td><td>Fred</td><td>Solo</td><td>available</td></tr>`;
let action = $(this).data('action');
if (action == 'add-top') {
$('#blockList').prepend($(fakerow))
} else if (action == 'add-bottom') {
$('#blockList').append($(fakerow))
} else if (action == 'remove-top') {
$('#blockList tr').first().remove()
} else if (action == 'remove-bottom') {
$('#blockList tr').last().remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table1">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Time (Local)</th>
<th class='collapsableHeader' onclick='collapseTable()'>Hash</th>
<th>Height</th>
<th>Effort</th>
<th>Found By</th>
<th>Pool/Solo</th>
<th>Status</th>
</tr>
</thead>
<tbody id="blockList"></tbody>
</table>
<hr>
<button data-action='add-top'>Add row to top</button>
<button data-action='add-bottom'>Add row to end</button>
<hr>
<button data-action='remove-top'>Remove row from top</button>
<button data-action='remove-bottom'>Remove row from end</button>
Why my tbody is not doing what I want, anyone can help me ?
This is my problem, in case I want to display in row but why that value just stay in column 1.2:
This is my jQuery:
$(function(){
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
success: function(response) {
console.log(response);
var counter = 0;
var obj = response.results;
var Content = ' ';
var x = 0;
Content += '<tbody>'; //opening tag tbody
for(var i=0;i<obj.length; i++)
{
Content += '<tr>';
Content += '<td>'+obj[i].name+'</td>';
Content += '<td>'+obj[i].height+'</td>';
Content += '<td>'+obj[i].hair_color+'</td>';
Content += '<td>'+obj[i].skin_color+'</td>';
Content += '<td>'+obj[i].eye_color+'</td>';
Content += '<td>'+obj[i].birth_year+'</td>';
Content += '<td>'+obj[i].gender+'</td>'
Content += '</tr>';
}
Content += '</tbody>';
$('#results').empty();
$('#results').append(Content);
}
});
});
var tbody=document.getElementById("results");
var table=document.getElementById("tableId");
var tbodyIndex= [].slice.call(table.tBodies).indexOf(tbody);
And this my html
<table class="table table-stripted table-bordered table-hover" id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
please help me , im newbie in javascript, oh yeah sorry for bad grammer, hope u guys help me , thank you
You don't have to add a tbody tag when your ajax response come in.
It's already in the DOM.
You can remove:
Content += '<tbody>';
Content += '</tbody>';
The HTML generated by your code is below.
Notice the two nested <tbody> elements, which disrupts the layout of your table.
GENERATED HTML
<table class="table table-stripted table-bordered table-hover " id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
<tbody>
<tr>
<td>Luke Skywalker</td>
<td>172</td>
<td>blond</td>
<td>fair</td>
<td>blue</td>
<td>19BBY</td>
<td>male</td>
</tr>
</tbody>
</tbody>
</table>
As Maarten van Tjonger has already answered, remove <tbody> from your Content string to avoid its duplication.
Rather than using empty() and append(), I've used html() to replace the contents of the <tbody> with the new HTML.
Also, you'll want to execute dataTable() on the <table> itself, not the <tbody>.
WORKING EXAMPLE
$(function() {
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
success: function(response) {
var obj = response.results,
Content;
for (var i = 0; i < obj.length; i++) {
Content += '<tr>';
Content += '<td>' + obj[i].name + '</td>';
Content += '<td>' + obj[i].height + '</td>';
Content += '<td>' + obj[i].hair_color + '</td>';
Content += '<td>' + obj[i].skin_color + '</td>';
Content += '<td>' + obj[i].eye_color + '</td>';
Content += '<td>' + obj[i].birth_year + '</td>';
Content += '<td>' + obj[i].gender + '</td>'
Content += '</tr>';
}
$('#results').html(Content);
$('#tableId').dataTable();
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-stripted table-bordered table-hover " id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
You are missing the quotes around your tbody id <tbody id=results> should be <tbody id="results"> and you are generating a second <tbody> in your JS which is not necessary. Otherwise your code runs fine so see this fiddle with the problems corrected.
i have a table that display data whenever a user clicks the start event button,but i need to know how to append the records when the user clicks the start button again,the previous record gets overridden
here is my javascript code
function DisplayData(downTime) {
console.log(downTime);
var newContent = '';
$.each(downTime.data, function (i, item) {
newContent += Hesto.Html.StartTR(item.downTime);
newContent += Hesto.Html.CreateTD(item.CategoryName);
newContent += Hesto.Html.CreateTD(item.StartTime);
newContent += Hesto.Html.CreateTD(item.EndTime);
newContent += Hesto.Html.CreateTD(item.Comments);
newContent = Hesto.Html.EndTR(newContent);
});
$('#DowntimeList').html(newContent);
}
and here is my html code:
<table id="Downtimetable" class="hesto">
<thead>
<tr>
<th>End Of DownTime</th>
<th>Category Name</th>
<th>Start Time</th>
<th>End Time</th>
<th>Comments</th>
</tr>
</thead>
<tbody id="DowntimeList">
</tbody>
<tfoot>
</tfoot>
</table>
Use append() instead of overwriting the html():
$('#DowntimeList').append(newContent);
As you suggested in the title of your question, append() it.
$('#DowntimeList').html(newContent);
Should be
$('#DowntimeList').append(newContent);
Simply use,
document.getElementById('DowntimeList').InnerHtml = document.getElementById('DowntimeList').InnerHtml+newContent
I want to get the entire column of a table header.
For example, I want to select the table header "Address" to hide the address column, and select the "Phone" header to show the correspondent column.
<table>
<thead>
<tr>
<th id="name">Name</th>
<th id="address">Address</th>
<th id="address" class='hidden'>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Freddy</td>
<td>Nightmare Street</td>
<td class='hidden'>123</td>
</tr>
<tr>
<td>Luis</td>
<td>Lost Street</td>
<td class='hidden'>3456</td>
</tr>
</tbody>
I want to do something like http://www.google.com/finance?q=apl (see the related companies table) (click the "add or remove columns" link)
Something like this would work -
$('th').click(function() {
var index = $(this).index()+1;
$('table td:nth-child(' + index + '),table th:nth-child(' + index + ')').hide()
});
The code above will hide the relevant column if you click on the header, the logic could be changed to suit your requirements though.
Demo - http://jsfiddle.net/LUDWQ/
With a couple simple modifications to your HTML, I'd do something like the following (framework-less JS):
HTML:
<input class="chk" type="checkbox" checked="checked" data-index="0">Name</input>
<input class="chk" type="checkbox" checked="checked" data-index="1">Address</input>
<input class="chk" type="checkbox" checked="checked" data-index="2">Phone</input>
<table id="tbl">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>Freddy</td>
<td>Nightmare Street</td>
<td>123</td>
</tr>
<tr>
<td>Luis</td>
<td>Lost Street</td>
<td>3456</td>
</tr>
</tbody>
Javascript:
var cb = document.getElementsByClassName("chk");
var cbsz = cb.length;
for(var n = 0; n < cbsz ; ++n) {
cb[n].onclick = function(e) {
var idx = e.target.getAttribute("data-index");
toggleColumn(idx);
}
}
function toggleColumn(idx) {
var tbl = document.getElementById("tbl");
var rows = tbl.getElementsByTagName("tr");
var sz = rows.length;
for(var n = 0; n < sz; ++n) {
var el = n == 0 ? rows[n].getElementsByTagName("th")[idx] : rows[n].getElementsByTagName("td")[idx];
el.style.display = el.style.display === "none" ? "table-cell" : "none";
}
}
http://jsfiddle.net/dbrecht/YqUNz/1/
I added the checkboxes as it doesn't make sense to bind the click to the column headers as you won't be able to toggle the visibility, only hide them.
You can do something with CSS, like:
<html>
<head>
<style>
.c1 .c1, .c2 .c2, .c3 .c3{
display:none;
}
</style>
</head>
<body>
<table class="c2 c3">
<thead>
<tr>
<th id="name" class="c1">Name</th>
<th id="address" class="c2">Address</th>
<th id="phone" class="c3">Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td class="c1">Freddy</td>
<td class="c2">Nightmare Street</td>
<td class="c3">123</td>
</tr>
<tr>
<td class="c1">Luis</td>
<td class="c2">Lost Street</td>
<td class="c3">3456</td>
</tr>
</tbody>
</table>
</body>
</html>
To hide a column, you add with Javascript the corresponding class to the table. Here c2 and c3 are hidden.
You could add dynamically the .c1, .c2,... in a style tag, or define a maximum number.
The easiest way to do this would be to add a class to each td that matches the class of the header. When you click the , it checks the class, then hides every td with that class. Since only the s in that column would hide that class, it would effectively hide the column.
<table>
<thead>
<th>Name</th>
<th>Address</th>
</thead>
<tbody>
<tr>
<td class="Name">Joe</td>
<td class="Address">123 Main St.
</tbody>
</table>
And the script something like:
$('th').click( function() {
var col = $(this).html(); // Get the content of the <th>
$('.'+col).hide(); // Hide everything with a class that matches the col value.
});
Something like that, anyway. That's probably more verbose than it needs to be, but it should demonstrate the principle.
Another way would be to simply count how many columns over the in question is, and then loop through each row and hide the td that is also that many columns over. For instance, if you want to hide the Address column and it is column #3 (index 2), then you would loop through each row and hide the third (index 2).
Good luck..
Simulating the Google Finance show/hide columns functionality:
http://jsfiddle.net/b9chris/HvA4s/
$('#edit').click(function() {
var headers = $('#table th').map(function() {
var th = $(this);
return {
text: th.text(),
shown: th.css('display') != 'none'
};
});
var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
$.each(headers, function() {
h.push('<th><input type=checkbox',
(this.shown ? ' checked ' : ' '),
'/> ',
this.text,
'</th>');
});
h.push('</tr></thead></table></div>');
$('body').append(h.join(''));
$('#done').click(function() {
var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
$.each(showHeaders, function(i, show) {
var cssIndex = i + 1;
var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
if (show)
tags.show();
else
tags.hide();
});
$('#tableEditor').remove();
return false;
});
return false;
});
jQuery('thead td').click( function () {
var th_index = jQuery(this).index();
jQuery('#my_table tbody tr').each(
function(index) {
jQuery(this).children('td:eq(' + th_index + ');').each(
function(index) {
// do stuff here
}
);
}
);
});
here's a working fiddle of this behaviour:
http://jsfiddle.net/tycRW/
of course, hiding the column with out hiding the header for it will have some strange results.
Im very new to html and javascript.
I want to get the content of element whenever the user click on a table row using javascript.
test.html
<html>
<head>
<script text="text/javascript">
function dispTblContents() {
var pName = document.getElementById("pName").value;
var pAddress = document.getElementById("pAddress").value;
var pEmail = document.getElementById("pEmail").value;
alert(pName + " " + pAddress + " " + pEmail);
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address </th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr onclick="dispTblContents();" >
<td id="pName">Ricardo Lucero</td>
<td id="pAddress">Mexico City, Mexico</td>
<td id="pEmail">rlucero#test.com</td>
</tr>
</tbody>
</table>
</body>
</html>
Whenever I click the row it displays undefined undefined undefined. I know my code is wrong but I really don't how to fix this. Can somebody please help me. Im very new to this thing. Thanks in advance.
You need innerHTML not value here, value is used for form elements.
<script text="text/javascript">
function dispTblContents() {
var pName = document.getElementById("pName").innerHTML;
var pAddress = document.getElementById("pAddress").innerHTML;
var pEmail = document.getElementById("pEmail").innerHTML;
alert(pName + " " + pAddress + " " + pEmail);
}
</script>
You might also want to look into jQuery if you're not using it yet, it makes selecting and manipulating HTML with Javascript a lot easier.
Try change value to innerHTML
Try to change value to innerHTML or innerText
document.forms[0].getElementsByTagId("pName").innerText;
A <td> tag doesn't have a value.
Use document.getElementById("pName").innerHTML instead.
I searched a lot for it too. Finally I get to see teaches's solution. This is an example that works:
...........
<head>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<% ArrayList<Student> students = StudentsManager.getInstance().getStudents(); %>
<body>
Choose a student <br>
<table>
<tr>
<td>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Student st : students){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=<%=st.getStudentId()%>');">
<td name = "title" align = "center"><%= st.getStudentId() %></td>
</tr>
<%}%>
...............
students is an ArrayList that contains objects of type Student(studentId, name).
The table displays all the students. Befor you click on a cell, click view source. You'll see:
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=1');">
<td name = "title" align = "center">1</td>
</tr>
Well in my case was "1". I didn't make the destination page yet.