Javascript: get content of table's cell (inside div) - javascript

I have a little problem with finding cell's id (and its content). Main table contains multiple divisions and each division contains one table with several cells. What I want is to display cell with id content_xx. My tables look like this:
<table id="MainTable"> // Main (global) table
<div id="divid_1"> // First div in main table
<table id="InfoTable"> // First div's table
<td id="title_10">CellTitle</td> // Cell #1
<td id="content_11">CellContent</td> // Cell #2
<div id="divid_2"> // Second div in main table
<table id="InfoTable"> // Second div's table
<td id="title_20">CellTitle</td> // Cell #1
<td id="content_21">CellContent</td> // Cell #2
// etc...
</table>
Function for finding it:
function FindContent(id)
{
t = document.getElementById("InfoTable").rows[0].cells.namedItem("content_"+id).innerHTML;
alert(t);
return;
}
I have onclick event which executes this function. It works for me only for first InfoTable, but it does not work when I try same thing on table #2 or further. I get this error: TypeError: document.getElementById(...).rows[0].cells.namedItem(...) is null. How can I fix this and why it does not work? Is it because of row[0]? If I change to row[1], for example, then it doesn't work at all. I can change structure of html but not completely.

** Solved by icecub **
The problem was that I was using same ID in divs, therefore, only first table would have been returned. I just needed to use different ID.

Related

Xpath clicking button within a td where row contains a specific text vlaue

I'm currently using Nightwatch to do some automated tests, but CSS selectors were extremely complex and did not do the job for me. I've instead started to look at XPath to do the job however the table in question is fairly complex.
I want to be able to .click() a button within a td value, where that specific row in the table contains a specific value. The table looks like this:
Username Email Display Name Buttons to Click (1st one wanted)
test test#example test (1st button)(2nd button)
test2 test2#example test (1st button)(2nd button)
Each of these values are within a tr > td so being able to find it is proving difficult. This is my currently XPath:
.click('/table[#id="admin-user-list"]/tbody/tr[td = "test2"]/td/button')
The HTML tree looks like this:
<div id>
<div class>
<table class>
<tbody>
<tr>
<td data-bind>(username)
<td data-bind>(email)
<td data-bind>(display name)
<td button>
(1st button)
(2nd button)
</tr>
</tbody>
Each row has its own tr with those exact tds inside.
Some help would be appreciated :)
.click('//table[#id="admin-user-list"]/tbody/tr[./td[text()='test2']/td/button')
logic: //table[#id="admin-user-list"]/tbody/tr[./td[text()='test2']
- tr with td that has text
/td/button -button in that row
but actually this is not really good idea to do that, as you are searching for that value in each column. Better to use combination of columnName+value
Let's check on that table sample: https://www.w3schools.com/css/css_table.asp
We'll search for table data in column by name, for example table column = Country, data = UK
//*[#id='customers']//tr/td[count(//*[#id='customers']//th[text()='Country']/preceding-sibling::*)+1][text()='UK']
again, logic is simple:
general locator is:
//*[#id='customers']//tr/td - we are searching for table data
with parameters: [text()='UK'] and position = same, as in column name [count(column_position)]
How to get column position:
just get column with needed text:
//*[#id='customers']//th[text()='Country'] and count it's preceding siblings:
//*[#id='customers']//th[text()='Country']/preceding-sibling::* , also we should add +1 , as we need current element's position. and count that staff, so here is the result: [count(//*[#id='customers']//th[text()='Country']/preceding-sibling::*)+1]
so having column position we can get general locator:
tableId = customers; columnName= Country; dataText = UK;
//*[#id='tableId']//tr/td[count(//*[#id='tableId']//th[text()='columnName']/preceding-sibling::*)+1][text()='dataText']
And here is locator to get hole row by data+columnName
//*[#id='customers']//tr[./td[count(//*[#id='customers']//th[text()='Country']/preceding-sibling::*)+1][text()='UK']]
and basically you can search anything inside of it, for example just add in the end
/td/button - to get button from it

Only highlight row in table with corresponding value of ID

I have a html table 'TemplateData' populated dynamically from a db table...so for example could end up like:
ID Name Age
1 John 23
2 Mick 27
3 Mark 29
When the user clicks an image on screen it will post back the corresponding ID value. From here I want to change the background colour of the associating row.
So for example '2' has been posted back in 'fid'. so I have tried...
function highlightRowInTable(fid) {
var dtable = $("#TemplateData");
dtable.addClass("highlightedRow");
}
However this highlightes the outer cells of the table. I only want to highlight the corresponding row.
Iv been messing around with parents and siblings but cant find any working examples on line...any ideas?
It looks like your code is selecting the entire table, and then applying a class to it, though it is hard to say for sure. If you have an event listener attached to your table, you should be able to get the child element that was clicked on and toggle its class.
document
.getElementById('table')
.addEventListener('click', function(event){
// now event refers to the part of the dom that was clicked on
console.log(event)
});
Though I'm not sure without looking at your code. if you already have listeners set up, you might need to give every row an id based on fid, so that your function could specify the id to add class to.
function highlightRowInTable(fid) {
$(fid).addClass("highlightedRow");
}
when you create your table you can add an attribute to your <tr> to help select it later when an image is clicked.
#foreach (var row in table)
{
<tr data-uid="#row[id]">
<td></td>
</tr>
}
function highlightRowInTable(fid) {
var rows = $('tr').filter('[data-uid="' + fid + '"]');
rows.addClass("highlightedRow");
}

Hide div if no table rows are visible

I have a few divs on a page each containing one table.
A user interacts with the table and hides some rows.
I want to hide the containing div if all the table rows in the containing table are hidden.
How can I do this in jQuery?
.div.mytable
table
tr
.div.mytable
table
tr
Demo
This hides the row you want to hide and hides it's parent div if all rows are hidden.
JS
$('.hide').click(function(){
// This hides the nearest <tr>
$(this).closest('tr').hide();
// Number of <tr> of it's <table>
var tableTrNumber = $(this).closest('table').find('tr').length;
// Number of <tr> already hidden of it's <table>
var tableTrHiddenNumber = $(this).closest('table').find('tr:hidden').length;
// If my tr number are equal to the number of hidden tr then hide the div
if(tableTrNumber == tableTrHiddenNumber)
{
$(this).closest('.mytable').hide();
}
});
Every style and HTML structure is just to show you how it works. Feel free to adapt it to your needs. Of course you've to respect the hierarchy of elements.
If you don't like the hide() function you can put whatever effect you want like a fade or accordion.
Hope this helps you.
You can target the containing div or put a class on each of the containing divs
<div class="containerDiv">
<table>
</table>
</div>
Use the simple jQuery .has() method
if($(".containerDiv table").has("tr")){
$(this).parent(".containerDiv").hide();
}
Wrap it in a function and call the function when ever the interaction happens.

How to get table id using Jquery?

In my Java program I have a List<DemoTable>.
List<DemoTable> demotable = new ArrayList<DemoTable>();
DemoTable is a class with id,name,and details variables.
I display these details using Jquery..
<table>
<c:forEach items="${modalAttribute.demotable}" var="demo">
<tr class="M_row_bg M_read">
<td><input type="checkbox" id="isDelete"/></td>
<td><label for="name">${demo.name}</label></td>
<td><label for="totalExperience">${demo.details}</label></td>
</tr>
<c:forEach>
</table>
Data will be displayed correctly ... but when check box is clicked I want to get Table row id:
$("#isDelete").click(function(){
if (this.checked){
alert('checked');
alert(demo.id);
} else {
alert('unchecked');
}
} );
I expect this alert to give the DemoTable id, but this alert does not show. Also, this click only works for the first row of the table.
How can I get the DemoTable id when I click the check box?
What does my code need to work with each row of table click event, not just the first row?
you're using #isDelete multiple times in the table. This is illegal, and the reason your code only works on the first row. Use a class instead.
your table rows don't even have an ID. They do however have an implicit index.
you should give your table an ID
you can use "event delegation" and just register a single click handler on a common parent element (i.e. the table) which then uses event bubbling to figure out which actual element was clicked. This can be more efficient than registering the exact same event handler explicitly on every matching element.
Try this instead:
$('#myTable').on('click', '.isDelete', function(){
if (this.checked) {
var rowId = $(this).closest('tr').index(); // row within table (0 based)
}
});

Retrieve all values of a dynamically generated html table

I have a html table displayed in a showmodal dialog window, the html-body has several divs, each div having several tables, tr and td within them.
The user will update entries within the input tag so i need to capture the change.
One such div looks like below. How to I retrieve all these values on a button click. I have heard of serialize() method. Will it work for all tag types, "insert","select", "option" etc etc.
<div>
<table>
<tr><td></td><td></td><td></td>
</tr>
</table>
<table>
<tr><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td>
</tr>
</table>
<table>
<tr><td></td>
</tr>
</table>
</div>
Apologies, writing my solution in a pseudocode fashion:
//I created a div container and then loop through all the divs
//then retrieve values using one of the below
$("classname > div[id]").each(function(){
var a= document.getElementsByName("name of the tag"); //by name
var b= document.getElementById("id of the tag"); //by id
var c= $("input[class='"+trd_id+"']:checked").val(); // for radio button
});
// loop by div counts and alert the values. Solved my problems

Categories

Resources