Change table td using javascript - javascript

I am new to Javascript so take it easy on me. I want to change data inside a table using javascript. I have looked everywhere for a suitable tutorial but I haven't found any. This is my code.
function trans() {
var table = document.getElementById("table");
var row = table.getElementsByTagName("tr")[2];
var td = row.getElementsByTagName("td")[0];
td.innerHTML = "Julius";
}
**css**
table {
width: 100%;
border-collapse: collapse;
font-family: calibri;
}
tr,
th,
td {
border: 2px solid black;
padding: 10px 10px 10px 10px;
}
thead {
background-color: black;
color: white;
}
tbody {
background-color: white;
color: black;
}
.center {
text-align: center;
}
.caption {
text-align: center;
}
button {
background-color: blue;
color: white;
border-radius: 5px;
height: 25px;
}
<html>
<body>
<table id="table" title="Employment status verses Living Conditions">
<caption>Employment status verses Living Conditions</caption>
<thead>
<tr>
<th colspan="3" class="caption">Employment status verses Living Conditions</th>
</tr>
<tr>
<th>Name</th>
<th>State</th>
<th>Condition</th>
</tr>
</thead>
<tr>
<td>Antony</td>
<td>Employed</td>
<td>Poor</td>
</tr>
<tr>
<td>Grace</td>
<td>Student</td>
<td>Wealthy</td>
</tr>
<tr>
<td>Jane</td>
<td>Sponsored</td>
<td>Self actualization</td>
</tr>
<tr>
<td>Christine</td>
<td colspan="2" class="center"><i>Unknown</i>
</td>
</tr>
<tr>
<td rowspan="2">James and John</td>
<td>Fishermen</td>
<td>Spiritual</td>
</tr>
<tr>
<td>Brothers</td>
<td>Disciples</td>
</tr>
</table>
<button onclick="trans()">Change name</button>
</body>
</html>
When I run the code it gives me the following error,
{
"message": "Uncaught TypeError: table.getElementByTagName is not a function",
"filename": "http://stacksnippets.net/js",
"lineno": 96,
"colno": 15
}
I have changed the getElementByTagName to getElementsByTagName but it is still giving me an error, What is wrong with my code and what can I do to fix it. Find my jsfiddle here

This works:
Code snippet
Try this:
function trans() {
var table = document.getElementById("table");
var row = table.getElementsByTagName("tr")[2];
var td = row.getElementsByTagName("td")[0];
td.innerHTML = "Julius";
}
You selected the first tr that has no td , only th in it and you also forgot "s" in "getElementsByTagName".
Because with "Tag" you can get more then 1 element you need to add "s" , when it's by ID it makes sense that you will get only 1 item therefor no "s" is needed.

You're missing an s in your last line of Code.
Also, data already contains the element you want to edit, so there's no need to call getElementsByTagName on data.
Change this Line
data.getElementByTagName("td")[0].innerHTML = "Julius"
To
data.innerHTML = "Julius";

This should suffice.
function trans() {
var table = document.getElementById("table"),
tr = table.getElementsByTagName('tr')[2],
td = tr.getElementsByTagName('td')[0];
td.innerHTML = "Julius";
}
Issues:
In order to select a certain key "[2]" you need to use .getElementsByTagName instead of .getElementsByTagName;
You're targeting the wrong tr. There are tr's in the table head. So even with fixing the number 1 issue, you would not get the correct result.

Related

HTML Table: border-collapse and visibility collapse of tr

I have a table with multiple lines, e.g.:
<table>
<tr id="line1"><td>Line</td><td>1</td></tr>
<tr id="line2"><td>Line</td><td>2</td></tr>
<tr id="line3"><td>Line</td><td>3</td></tr>
</table>
Now, in javascript (based on a radio input field) I want to remove (e.g.) #line3 by adding a visibility:collapse, something like:
document.getElementById("line3").style = "visibility:collapse";
The special thing about #line3 is that it has a border-top:
<style>
table {
border-collapse: collapse;
}
#line3 {
border-top:1px solid black;
}
</style>
The problem I have with that: When I "collapse" #line3 the border persists, eventhough the element "does not exist". I guess this should be due to the border-collapse in the table style "inheriting" a border element on the previous tr element? How can I fix that issue?
EDIT: I'd like to keep the javascript like that. Of course I could remove/readd the style element but there should be a different way to solve this?!
Of course I could remove/readd the style element
I think this means you don't want to mess with the border-top property when changing the row's visibility, correct?
In that case, it looks like your only option is to use display:none instead of visibility:collapse[1], which is unfortunate because then your table might have the wobbly effect that visibility:collapse was designed to prevent.
[1] https://drafts.csswg.org/css-tables-3/#visibility-collapse-track-rendering is not crystal clear, but looks like the spec prescribes the behavior you don't want. And chrome and firefox act a bit differently in the visibility:collapse case. https://jsfiddle.net/dgrogan/gLqo9s4w/2
let visible = 1;
toggle.onclick = function() {
line3.style.visibility = visible ? "collapse" : "visible";
//line3.style.display = visible ? "none" : "table-row";
visible = !visible;
}
table {
border-collapse: collapse;
}
td {
border: 1px solid lime;
}
#line3 {
border-top: 2px solid black;
}
<table>
<tr id="line1">
<td>Line</td>
<td>1</td>
</tr>
<tr id="line2">
<td>Line</td>
<td>2</td>
</tr>
<tr id="line3">
<td>Line</td>
<td>3</td>
</tr>
</table>
<br><br>
<button id=toggle>toggle</button>
<P>
https://drafts.csswg.org/css-tables-3/#visibility-collapse-track-rendering
</P>
Have you tried "display: none"?
document.getElementById("line3").style = "display: none";
Or maybe you could try setting the border-top to 0 which should hide it.
document.getElementById("line3").style = "visibility:collapse; border-top: 0";
.cssText
You can edit the whole inline [style] attribute by using .cssText:
document.getElementById("line3").style.cssText = "visibility:collapse; border-top:0px";
This allows you to set visibility and border properties (and more if you want) in one line.
Demo
document.getElementById("line3").style.cssText = "visibility:collapse; border-top:0px";
table {
border-collapse: collapse;
}
#line3 {
border-top: 1px solid black;
}
<table>
<tr id="line1">
<td>Line</td>
<td>1</td>
</tr>
<tr id="line2">
<td>Line</td>
<td>2</td>
</tr>
<tr id="line3">
<td>Line</td>
<td>3</td>
</tr>
</table>
You have several solutions to do this, with Jquery:
$('#line1').hide();
//OR
$('#line1').css('visibility','collapse');
//OR
$('#line1').css('display','none');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr id="line1"><td>Line</td><td>1</td></tr>
<tr id="line2"><td>Line</td><td>2</td></tr>
<tr id="line3"><td>Line</td><td>3</td></tr>
</table>
You can also use Javascript directly with the getElementById property:
document.getElementById("line1").style.display = "none";
Or
document.getElementById("line1").style.visibility = "collapse";

How to get the value of 2nd td in html table on click of first td using jquery

I have a requirment where i need to get the value of 2nd td in html table on click of first column in html table. I am using jquery to achieve this.
$('.tbody').on('click','tr td:nth-child(1)', function () {
var id = $(this).closest("td").find('td:eq(1)').text();
alert(id)
});
I am using onclick function to get the value of second td as shown in the above code.But i am getting an empty alert. I dont know where i have gone wrong please help.
As per my understanding $(this).closest("td").find('td:eq(1)').text() should search for next td and .text() method should display the value within td isn'tit?
Below snippet will reflect the issue mentioned above
Please help!
Thanks in advance!
$(function () {
$('.tbody').on('click','tr td:nth-child(1)', function () {
var id = $(this).closest("td").find('td:eq(1)').text();
alert(id)
});
});
#items {
border-collapse: collapse;
width: 100%;
}
#items th {
background-color: #009999;
color: white;
border : 1px solid;
}
#items td{
border : 1px solid;
}
#items tbody{
height:200px;
overflow-y:auto;
}
#items thead,.tbody{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table class="table table-striped table-bordered table-hover table-condensed" style="width: 300px; " id="items">
<thead>
<tr>
<th style="width:100px;">Fee Type</th>
<th style="width:100px;">Charges per Qty</th>
<th style="width:100px;">Qty</th>
</tr>
</thead>
<tbody class="tbody">
<tr>
<td style="width:100px;">a</td>
<td style="width:100px;">b</td>
<td style="width:100px;">c</td>
</tr>
<tr>
<td style="width:100px;">d</td>
<td style="width:100px;">e</td>
<td style="width:100px;">f</td>
</tr>
</tbody>
</table>
</div>
The issue with your logic is that this refers to the td already, so closest('td') isn't going to get the element you need. It's also not the parent of the td you want to target either, so find() won't work. You need to use closest('tr') instead:
var id = $(this).closest("tr").find('td:eq(1)').text()
However, the simplest method to achieve this would be to just use next() as the td elements are siblings:
$(function() {
$('.tbody').on('click', 'tr td:nth-child(1)', function() {
var id = $(this).next().text();
console.log(id);
});
});
#items {
border-collapse: collapse;
width: 100%;
}
#items th {
background-color: #009999;
color: white;
border: 1px solid;
}
#items td {
border: 1px solid;
}
#items tbody {
height: 200px;
overflow-y: auto;
}
#items thead,
.tbody {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table class="table table-striped table-bordered table-hover table-condensed" style="width: 300px; " id="items">
<thead>
<tr>
<th style="width:100px;">Fee Type</th>
<th style="width:100px;">Charges per Qty</th>
<th style="width:100px;">Qty</th>
</tr>
</thead>
<tbody class="tbody">
<tr>
<td style="width:100px;">a</td>
<td style="width:100px;">b</td>
<td style="width:100px;">c</td>
</tr>
<tr>
<td style="width:100px;">d</td>
<td style="width:100px;">e</td>
<td style="width:100px;">f</td>
</tr>
</tbody>
</table>
</div>
Just change the closest element (td to tr) and you will get the expected result
var id = $(this).closest("tr").find('td:eq(0)').text();

Changing border left color based on value

I have a table where I want each row's border-left to differ based on priority level.
My HTML:
<tr id= "rows">
<td data-title="Link"><img src="form_blank.png" title="Agreement" width="40"/> ${gr1.short_description.getDisplayValue()}</td>
<td data-title="State"> ${gr1.state.getDisplayValue()} </td>
<td data-title="Due" input="date" data-date-format="MM/DD/YYYY">${gr1.due_date.getDisplayValue().substring(0,10)} </td>
</tr>
My Javascript:
<script>
function bordercolor() {
var leftborder = document.getElementById("rows");
if (${gr1.priority.getDisplayValue()} = 1){
leftborder.style.borderLeft = "solid 10px #b30000";}
else if (${gr1.priority.getDisplayValue()} = 2){
leftborder.style.borderLeft = "solid 10px #ffa500";}
else if (${gr1.priority.getDisplayValue()} = 3){
leftborder.style.borderLeft = "solid 10px #ffff00";}
else if (${gr1.priority.getDisplayValue()} = 4){
leftborder.style.borderLeft = "solid 10px #7fbf7f";}
else {leftborder.style.borderLeft = "solid 10px #006600";}
}
</script>
Any suggestions on what I'm doing wrong?
I'm not sure what ${...} means inside your code, hopefully I'm not missing something obvious but it's nothing I could recognize as valid. It smells to some preprocessing replacement logic but without confirmation is hard to say for sure.
Something else that is wrong at first sight is the fact that you're using assign operator (=) on the if statement instead of the equal operator (==)
Another problem is that tr can't take a border. Below you'll find how I would implement this. Notice the use of css classes instead of manipulating directly the element border. I'm also asigning an id to the table and using this control to apply styles instead of rows
HTML
<table id="table">
<tr>
<td data-title="Link"><img src="form_blank.png" title="Agreement" width="40"/> ${gr1.short_description.getDisplayValue()}</td>
<td data-title="State"> ${gr1.state.getDisplayValue()} </td>
<td data-title="Due" input="date" data-date-format="MM/DD/YYYY">${gr1.due_date.getDisplayValue().substring(0,10)} </td>
</tr>
</table>
CSS
.priority-1 td:first-child {
border-left: solid 10px #b30000;
}
.priority-2 td:first-child {
border-left: solid 10px #ffa500;
}
.priority-3 td:first-child {
border-left: solid 10px #ffff00;
}
.priority-4 td:first-child {
border-left: solid 10px #7fbf7f;
}
.priority-other td:first-child {
border-left: solid 10px #006600;
}
JAVASCRIPT
function bordercolor() {
var priority = ${gr1.priority.getDisplayValue()};
var table = document.getElementById("table");
if (priority <= 4)
table.className = "priority-" + priority;
else
table.className = "priority-other";
}
DEMO
You should be styling the leftmost td, you can't have a different left border on a row
The id attribute should be unique, rows would be better as a class
Leverage the variables you have when possible. Would this work?
<tr class= "rows" data-priority="${gr1.priority.getDisplayValue()}">
<td data-title="Link"><img src="form_blank.png" title="Agreement" width="40"/> ${gr1.short_description.getDisplayValue()}</td>
<td data-title="State"> ${gr1.state.getDisplayValue()} </td>
<td data-title="Due" input="date" data-date-format="MM/DD/YYYY">${gr1.due_date.getDisplayValue().substring(0,10)} </td>
</tr>
And css like this, targeting the data-priority attribute
.rows[data-priority="1"] td:first-child{ border-left: 2px solid #234324;}
.rows[data-priority="2"] td:first-child{ /* your css for this one */}
.rows[data-priority="3"] td:first-child{ /* your css for this one */}
/* and so on */

hide/show tbody of dynamically created tables on click at thead

As you can see after you run the code, i have multiple tables, let us assume they were dynamically created with PHP. I try to hide/show the entire tbody of a table if i click at it's thead.
I could just give each table it's own id and write the jquery code for each table... but since the tables are dynamically created, i can't solve it like this.
The current version of my jquery script toggles all tbody's if i click on a thead, instead of only the thead of the table which i actually clicked.
My only idea to solve this would be to also create the jquery code dynamically (but im not sure if this will actually work), but before i try this, does someone know if there is an easier solution?
I thought about something like this:
$("this tbody").css("display","none");
So that it only selects the tbody of the thead which i actually clicked on.
var main = function()
{
$toggle = true;
$("thead").click
(
function()
{
if ($toggle)
{
$toggle = false;
$("tbody").css("display","none");
}
else
{
$toggle = true;
$("tbody").css("display","");
}
}
);
}
$(document).ready(main);
table, td {
border: 1px solid black;
}
td {
color: red;
display: block;
max-width: 120px;
white-space: nowrap;
overflow-x: auto;
background-color: blue;
}
th {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr><th id="here1">First Table</th></tr>
</thead>
<tbody>
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
</tbody>
</table>
<table>
<thead>
<tr><th id="here1">Second Table</th></tr>
</thead>
<tbody>
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
</tbody>
</table>
First, instead of using $('tbody'), use this
Second, instead of managing variables for visibility, use toggle function
var main = function() {
$("thead").on("click", function() {
$(this).parents("table").find("tbody").toggle();
});
}
$(document).ready(main);
table,
td {
border: 1px solid black;
}
td {
color: red;
display: block;
max-width: 120px;
white-space: nowrap;
overflow-x: auto;
background-color: blue;
}
th {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th id="here1">First Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
<tr>
<td>C</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th id="here1">Second Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
<tr>
<td>C</td>
</tr>
</tbody>
</table>
try with
$(this).parent().find('tbody').css("display","none");
you can use .next() https://api.jquery.com/next/
$(this).next("tbody").css("display","none");
or better yet use toggle https://api.jquery.com/toggle/
$(this).next("tbody").toggle();
<table class="table" id="item"style="display:none;">
<tbody style="height:0px;width:82%; display:table;"></tbody>
</table>
and using script
<script>`enter code here`
document.getElementById("item").style.display = "block";
</script>

Container element inside of a table that holds rows

I am dynamically inserting a table row (or multiple rows) into a table upon an ajax call's return. I am looking to accomplish this by having an empty container type element inside of my html table that I can insert <tr> elements into. As I have seen from other posts, a div cannot hold a tr element, so my question is, is there a particular way that I can insert the html for row(s) into a table? It must be dynamic in nature, or in other words I need to be able to hold more than just one <tr>.
You can append to last row of table.
<table>
<tr><td>First Row</td></tr>
<tr><td>Middle Row</td></tr>
<tr><td>Last Row</td></tr>
</table>
<script>
$( "#tableid tr:last" ).append(
</script>
Assuming you aren't using jQuery, you can do something like this:
var myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var row = myTable.insertRow(myTable.rows.length);
You can then insert cells using insertCell on row.
Alternatively, if you have jQuery,
$("#myTable").append("<tr><td>Table Row with cell!</td></tr>");
I'm not sure why you wouldn't just use the <table> element directly, but you can use <tbody> elements as row containers within a table.
onload = function(){
document.getElementById("aButton").onclick = addRow.bind(null, "a");
document.getElementById("bButton").onclick = addRow.bind(null, "b");
}
function addRow(id) {
var r = document.getElementById(id).insertRow(-1);
var c = r.insertCell(-1);
c.innerHTML = "Row added at " + new Date().toLocaleTimeString();
}
body {
font-family: sans-serif;
font-size: 12px;
}
table {
border-collapse: collapse;
margin: 8px 0;
}
td {
border: 1px solid #ccc;
padding: 1px 2px;
}
<button id="aButton">Add row to 'A'</button>
<button id="bButton">Add row to 'B'</button>
<table>
<tbody><tr><td>Before A</td></tr></tbody>
<tbody id="a"></tbody>
<tbody>
<tr><td>After A</td></tr>
<tr><td>Before B</td></tr>
</tbody>
<tbody id="b"></tbody>
<tbody><tr><td>After B</td></tr></tbody>
</table>

Categories

Resources