Setting TD value from previous TD - javascript

I have a table that is filled in with values dependant on a previous page
those avlues are filled in with struts apparently
but I'm not very good with all that stuff so is there a simple was I can do something like this, either with HTML only or maybe a small javascript I can put in tha page?
<Table>
<TR>
<TH>ID</TH>
<TD><s:property value="groupID" /><TD> <--Number generated by the page with struts
</TR>
<TR>
<TH>ID Value</TH>
<TD>foobar</TD> <-- the text I want to add in dependant on the number from the previous TD
</TH>
</Table>
so, is there a simple way to go about doing this? HTML, CSS, JavaScript solution maybe?

Given that exact HTML, a simple script like this will do it. But if you don't know JavaScript, you should really learn it so that you understand what you're doing.
<body>
<Table>
<TR>
<TH>ID</TH>
<TD><s:property value="groupID" /><TD>
</TR>
<TR>
<TH>ID Value</TH>
<TD>foobar</TD>
</TR>
</Table>
<!-- The script is here so it won't run until the TABLE has loaded -->
<script type="text/javascript">
// This is a map of the struts values to your values
var valueMap = {
"1": "foo",
"2": "bar",
"3": "baz"
};
// Browser compatibility. Older IE uses 'innerText' instead of 'textContent'
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
// Get all the TD elements on the page
var tds = document.getElementsByTagName('td');
// Get the text content of the first TD (index 0)
var text = tds[0][textContent];
// Get the value from the map using the text we fetched above
var value = valueMap[text];
// Set the text content of the second TD (index 1) to the mapped value
tds[1][textContent] = value;
</script>
</body>

Assuming you want to place the value 'groupID' (set in the first tr's td) into the second row's td element, then the following jQuery will do the trick:
$(document).ready(function() {
// Scrape the XML out of the TD containing the xml
var tdXml = $('table tr').eq(0).find('td').html();
// Grab the value of the value attribute (groupID)
var value = $(tdXml).attr('value');
// Set this value in the second row's TD
$('table tr').eq(1).find('td').text(value);
}​);​
jsFiddle here

Related

Javascript get the last td of a table to remove/delete it

How can I get the last td of a table and remove it? It should be only JS, no jquery.
I tried this:
e.target.parentNode.querySelector("td:lastcell").remove();
var t = document.getElementById("test"); // The table
var lastTD = t.querySelector("TD:last-of-type");
console.log ("Text: " + lastTD.innerText);
<table id="test">
<tr>
<td>A</td>
<td>B</td>
</tr>
</table>
element.children should get you all the children as an array you can get the last child simply by element.children[element.children.length -1] and do whatever you want with it.
Also if your table has an id you can get the last td by using document.querySelect('#table-id td:last-child') or use document.querySelectAll('#table-id td:last-child') to get all the last tds

Getting element of a table with ID

Been having a great experience here so far!
Anyway, in coding my console bot, i encountered a problem. I wish to obtain some text data from a table, this table records a history of input into the site. But his table has no id and only has a class.
so here is the site element codes:
<div id="game">
<div class="gameTop">
<div class="right">
<div class="scroll">
<table>
<tbody>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
</tr>
I wish to get var xxx = "...." which corresponds to ddd. I have tried getElementbyClassName('scroll') but it gives me the table. Which is expected.
I am stuck at how to I delve deeper into the codings.
If you're using jQuery, you can use the :get() selector to specifically target the 4th <td> element and text() to retrieve the content.
var dd = $('table td:eq(3)').text();
Here's a fiddle with an example.
Edit
In case you need to get it through #game, you can quickly modify the selector to:
var dd = $('#game table td:eq(3)').text();
You should be able to get the table rows as follows:
var rows = document.getElementsByTagName("table")[0].rows;
var cell = rows[0].cells[4];
var value = cell.innerHTML
In this case, I prefer XPath. See code below:
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
var theDddNode = getElementByXpath("//td[contains(text(),'ddd')]");

Use javascript to Transfer Text

I have got 3 tables in html that at a certain time, i want to move text from 1 table will move to another. Can someone show me a javascript function ( just a few lines long - don't spend too long) that can transfer text from one td to another.
Transferring ONE td value to another:
Well if you assign a td an ID (ex. "firstTD", "secondTD"), you could store it's value in a variable (ex. "tdToMove"):
var tdToMove = document.getElementById("firstTD").innerHTML;
document.getElementById("secondTD").innerHTML = tdToMove;
Note: This will only copy the innerHTML of a single td, and duplicate it on the other. If you wish to clear the first entry, run:
document.getElementById("firstTD").innerHTML = "";
to render the first td 'blank'.
You will have to experiment to find a way to move ALL values to the other table, this was just a pointer.
Also, If the text is moving from table to table, and the tables remain identical, why not just place the input in both to begin with, OR, simply run a code to duplicate the table when you would like to move the data?
You can use Node.textContent property to get and set the text of a Node.
Here is a link about it:https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
I have made a fiddle to show you that in action: https://jsfiddle.net/3dep0msg/
In this fiddle i transfer the text of cell1 to cell2 and add it to the text of cell2.
I use textContent and not innerHTML property, because you wanted to transfer ONLY text!
function copyTextFromCell(id1,id2){
var cell1= document.getElementById(id1);
var cell2= document.getElementById(id2);
cell2.textContent = cell2.textContent+cell1.textContent;
}
copyTextFromCell("cell1","cell2");
if you want to do this using jquery.
<table id="table1">
<tr>
<td>1,1</td>
<td>1,2</td>
</tr>
<tr>
<td>2,1</td>
<td>2,2</td>
</tr>
</table>
<table id="table2">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
$('#table1 tr').each(function (indexR, element) {
$(this).find('td').each(function (index, element) {
var table2Rows = $('#table2 tr');
var table2Row = table2Rows.eq(indexR);
var table2Column = table2Row.find('td');
var table2cell = table2Column.eq(index);
table2cell.html( $(this).html());
});
});
working fiddle.

get jsonArray from table

I have a table and need to build json array. I need value from 1 and 4 column of table.
HTML
<table class="table table-striped" id="development_mapping">
<thead>
<tr>
<th>Visual Feature</th>
<th>Step</th>
<th>Output</th>
<th>Data Feature</th>
</tr>
</thead>
<tbody>
<tr><td>color</td>
<td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
<td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
<td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>
</table>
Here is my solution, a function to made an json array from table
JAVASCRIPT
var jsonArray = {};
$('#development_mapping').find('tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
I have done, but not understand, why I get " " from value of 4 column. I mean, why variable in variable is always getting " "
This is my DEMO
Your selector: $('#development_mapping').find('tr') is selecting all <tr> tags in the table. Even the one in the <thead>! The <thead> doesn't have <td> tags, so that's where the " " is coming from.
Try this:
$('#development_mapping').find('tbody tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
You are using .text() but there is no actual text in your 3rd td tag.
try this maybe?
variable : $(this).find('td:eq(3) input').val()
There are 2 problems with your code.
Remove the surrounding <tr> in your table head definition.
Use this to access input value
variable: $(this).find('td:eq(3) > input').first().val()
$.find() will return a collection and you'll need to get the first object of the collection for further use. Plus, you'll need to search for input inside the cell, not the cell itself.
Here is the working fiddle: http://jsfiddle.net/toshkaexe/7q3KP/

Optimizing Jquery iteration through table columns comparing with existing row

I'm trying to write a function to add color to a table based on a reference which is one of the top rows of the table. There are several questions in SO mentioning row based iteration but not so much about column.
The structure of the table is something like:
<table id="data">
<tr>
<th rowspan="2">Name</th>
<th rowspan="2">Selection</th>
<th rowspan="2">Title</th>
<th rowspan="2">Info1</th>
<th rowspan="2">Info2</th>
<th colspan="10">Data</th>
</tr>
<tr>
<th>001</th>
<th>002</th>
<th>003</th>
<th>004</th>
<th>005</th>
<th>006</th>
<th>007</th>
<th>008</th>
<th>009</th>
<th>010</th>
</tr>
<tr id="ref_control">
<td></td>
<td>RefName</td>
<td></td>
<td></td>
<td></td>
<td>A</td>
<td>B</td>
<td>J</td>
<td>L</td>
<td>Z</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox"/></td>
<td>Entity 1</td>
<td>Info...</td>
<td>More info...</td>
<td>Even more...</td>
<td>A</td>
<td>T</td>
<td>M</td>
<td>L</td>
<td>Z</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>2</td>
<td>5</td>
</tr>
(...)
</table>
In addition I'm using JQuery and the JQuery column cell select plugin to perform the mentioned task.
The Javascript code looks like this:
$(document).ready(function() {
// Colorize table based on matches
// Number of Data entries - Count on the reference (2nd row)
// and only 5th column onwards (index starts at 0)
var datasize = $("#data tr:eq(2) td:gt(4)").length;
// Start with column 6 (index starts at 1)
var begin = 6;
for (var i = begin; i < begin + datasize; ++i) {
var curCol = $("#data td").nthCol(i);
var ref = curCol.eq(0).text();
curCol.not(curCol.eq(0)).each(function() {
var data = $(this);
if (data.text() == '') {
data.addClass("black");
} else if (data.text() != ref) {
data.addClass("color");
}
});
}
});
A working example can be visualized here. In the example the table has only 9 rows and 10 data columns. The actual page I'm trying to optimize has 20 rows and 90 data columns.
Using the mentioned Javascript extensions/plugins the big sized table poses no threat to the Google Chrome browser taking a few seconds to load, however Opera, Firefox and Internet Explorer have a hard time running the function or end up asking for user interaction to stop the script from running.
So my question is aimed at both alternatives to the column select plugin or ways to optimize the code such that I don't kill almost all browsers except Google Chrome.
Edit: Changes according the the two comments from #Pointy
You can easily get 10x faster code if you want. Just save references once and go row by row instead of column by column. It doesn't become more complicated yet it performs much better. The reason is that your plug-in hides the abstraction that your table is made of rows that are made of columns. And not the other way around. Emulating the second version can be costy as you noticed in this example.
You may also use DOM properties instead of jQuery methods. They are really straightforward.
// get text (modern browsers || IE <= 8)
var text = elem.textContent || elem.innerText;
// set class
elem.className = "black";
your final code will be something like:
var refcells = $("#data tr:eq(2) td:gt(4)");
var datasize = refcells.length;
// Start with column 5
var begin = 5;
var refs = [];
var i = begin;
refcells.each(function () {
refs[i++] = $(this).text();
});
$("#data tr:gt(2)").each(function () {
var cells = $("td", this);
for (var i = begin; i < begin + datasize; i++) {
var elem = cells[i];
var text = elem.textContent || elem.innerText;
if (!text) {
elem.className = "black";
} else if (text != refs[i]) {
elem.className = "color";
}
}
});
Doing what you're doing is going to be very computationally intensive. Since your table layout seems pretty regular, I'd just completely ditch that nthCol() thing (for this page anyway) and do your work by iterating over the table once:
Grab the "key" row first, and save it
Loop through each relevant <tr>, and for each one get the <td> elements and iterate over them as a raw node list, or as a jQuery list. Either way it should be a lot faster.
In the second loop, you'll do the same logic you've got (although I'd use addClass() and removeClass()), referring back to the saved "key" row for each cell.
In your current loop, you're re-building the jQuery object of every <td> in the table for each column, and then you're doing that nthCol() work! That's a lot of work to do if you do it once, so repeating that for every single column is going to really drag that CPU down. (On IE6 - especially with all those "class" changes - I bet it's almost unbearably slow.)
edit — I looked over that code (for the plugin), and while it looks like it was competently implemented it doesn't have any "magic tricks". All it does is iterate through all the table cells you give it and checks whether or not each cell is in fact in the "nth" column. Thus, your iteration will perform that test on every cell in the table for every column you care about. In your 90x20 table, that'd be about 85 iterations through all 1800 cells. And that's before you do your work!

Categories

Resources