need to access current TR or TD - javascript

I have to change the table row color based on some business logic. I have limited access.
I have PHP code which decide TD content...from that TD I have to change the current TR background color.
jQuery can help, as it is having lot of traverser and accesser.
code I am writing is
<script type="text/javascript">$(this).closest("td").css("border", "1px solid red");</script>
But not able to access the current TD or TR

Instead of using this, give the element an id and get it using jQuery. In your code, this points to nothing. like:
<table><tr><td> <input id="myInput" type="text" /> </td></tr></table>
//If you want to access the td
$('#myInput').closest("td").css("border", "1px solid red");
//If you want to access the tr
$('#myInput').closest("tr").css("background", "red");

here you can use parents() funciton.
if your element is $('#el') then following will give you nearest td and tr
$('#el').parents('td').first();
$('#el').parents('tr').first();
then you can apply operation like below
$('#el').parents('td').first().css("border", "1px solid red");
$('#el').parents('tr').first().css("border", "1px solid red");

Assuming the worst case, where you have nested tables and you cannot change current TD attributes, than print an empty span within it this way:
<table>
<tr>
<td>Content 1
<table>
<tr>
<td>Content 2<span data-class="very_important" /></td>
</tr>
</table>
</td>
</tr>
</table>
Than add class to (first or last) parent TR like this:
$(function() {
$('span[data-class]').each(function(n) {
var highlightClass = $(this).attr('data-class');
$(this).parents('tr:first').addClass( highlightClass );
$(this).remove(); /* Optional */
});
});
Now your TR has class and you can style it (and its children) the way you like. Result code:
<table>
<tr>
<td>Content 1
<table>
<tr class="very_important">
<td>Content 2</td>
</tr>
</table>
</td>
</tr>
</table>

You need some way to target the TD content or the TD itself. If the content was unique you could search for a keyword or phrase. Either way, you need a selector - $(this) is just a reference to the jquery object once inside a handler.
EDIT
I thought about it a bit more and here's something you could try. Since you only have access to the content, could you add something to it like UPDATED? If so, then you could add that keyword and with jQuery we can add in the border, background and remove the keyword like this:
​<table cellpadding="5px" cellspacing="5px" border="1px">
<tr><td>*UPDATED*Apple</td><td>Pie</td></tr>
<tr><td>Orange</td><td>Crush</td></tr>
</table>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
-
var $updatedContent = $('td:contains("*UPDATED*")');
$updatedContent.closest('td').css('border', '1px solid red').closest('tr').css('background','green');
$updatedContent.text($updatedContent.text().replace('*UPDATED*', ''));
​

Related

How can I hide the table cells contents dynamically using plain javascript?

I am creating a table in plain JavaScript, and filling it up using onClick listener event in two ways - either clicking on a external button, or clicking on one of the cells itself.I am not able to hide the contents of my table cells dynamically i.e.I want to hide them when rendering values in them, which I want to unhide/display later-on on some other event.
I have already tried conventional methods available viz.
td {display: none;}, and td {visibilty: hidden}
I have also tried inline CSS style method to hide the cell contents, but all these methods blank the table itself i.e. oblivate the cell borders themselves.
<body>
<div class="container-fluid">
<table id="myelement">
<tr>
<td> </td>
... .... ...
<td> </td>
</tr>
</table>
</div>
</body>
<script>
...
for(let i=0;i<mycount;i++){
for(var t=0;t< Math.floor(Math.random()*td.length);t++){
td[n[i]].firstChild.nodeValue='X';
}
}
...
</script>
All the techniques available blank the table itself i.e. oblivate the cell borders themselves.
There are a number of ways to do this, and some other ways might be better depending on the content of your table cells. But assuming it's just text, one way you could hide the cell contents would be to make the fontSize of the cell equal to 0. See this example:
hide.addEventListener("click", function(event) {
document.getElementById("table").rows[1].cells[1].style.fontSize = 0;
});
show.addEventListener("click", function(event) {
document.getElementById("table").rows[1].cells[1].style.fontSize = null;
});
table, td, th {
border: 1px solid black;
}
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
<button id="hide">Hide Cell "Smith"</button>
<button id="show">Show Cell "Smith"</button>

How to select the text of respective table data separately under table row with jQuery

This is the code
<tbody id="table-body">
<tr>
<td id="c1">AAA0</td>
<td id="c2">2%</td>
</tr>
</tbody>
I want to select data of ID c1 under < tr > tag.
I am using this jQuery code but it is selecting whole text under < tr > tag.
$("#table-body").on('click','tr',function(e){
e.preventDefault();
console.log($(this).text());
})
I am getting AAA02% as the output if this code.
I want to select AAA0 and 2 separately.
How to do it ?
Since there is more than one td element in each clicked tr element, you have to loop through each of them to get the text individually.
You can use find() and each() like the following way:
$("#table-body").on('click','tr',function(e){
$(this).find('td').each(function(){
console.log($(this).text());
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="table-body">
<tr>
<td id="c1">AAA0</td>
<td id="c2">2%</td>
</tr>
</tbody>
</table>
Try this:
console.log($(this).find('.c1').text());
And use class attribute instead of id
You are getting all text inside tr because you are binding click event on the tr and so $(this) refers to thetr you clicked.
To get AAA0 only, you can use children() and pass id to select a specific td
$("#table-body").on('click','tr',function(e){
console.log($(this).children('#c1').text());
});
But since you are assinginig id to the td's, you can also directly attach the click event to the td as
$("#table-body #c1").on('click','tr',function(e){
console.log($(this).text());
});

How to remove <br> and everything after that?

If I do the following is fine:
<div id="results">
<p>Hello<br>there</p>
</div>
$($("#results p").children('br').get(0).nextSibling).remove();
I get: hello
But if I do:
<th class="infobox">Head</th>
<td>Hello<br>there</td>
var newLineRemove = $(".infobox td").children('br').get(0).nextSibling();
$wikiDOM.find(newLineRemove).remove();
Gives me
Uncaught TypeError: Cannot read property 'nextSibling' of undefined
That is because .get(...) returns a DOM element not a jQuery object.
In the first example you're using $(...) to convert that DOM element to a jQuery object but you're not doing that in the second example.
This will convert the DOM element to a jQuery element and get rid of the error
var newLineRemove = $($(".infobox td").children('br').get(0).nextSibling);
But it won't do what you want it to do because as #Forty3 said "the <td> isn't inside the ..infobox"
This seems to work but I've probably made things more complicated then they have to be:
$(function(){
var td = $(".infobox").next();
if(td.find("br").length){
$(td.contents().get().reverse()).each(function(){
$(this).remove();
if(this.tagName == "BR"){
return false;
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<th class="infobox"></th>
<td>Hello<br>there</td>
</table>
I've simplest solution for this, try this one:
$('td').each(function() {
$(this).html($(this).html().split('<br>')[0]);
});
li {
margin-bottom: 10px;
}
#usp-custom-3 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<th class="infobox"></th>
</tr>
<tr>
<td>Hell
<br>there</td>
</tr>
<tr>
<td>Hello
<br>there<br>there</td>
</tr>
</table>
Your code doesn't work because the ".infobox td" selector is looking for a td element inside an .infobox element, but in your HTML the td immediately follows the .infobox.
If you want something that is very similar to your existing JS but working with that HTML (noting that td and th elements need to be inside a tr in a table) you can do this:
$($(".infobox").next().children("br")[0].nextSibling).remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<th class="infobox"></th>
<td>Hello<br>there</td>
</tr>
</table>
That is, use .next() to get the element following the .infobox, get that element's child br elements, take the first one's .nextSibling, then wrap it in a jQuery object so that you can call .remove().
EDIT: Note that if there were multiple rows with similar elements the above code would only do the removal on the first one. If it were my code I would probably select all of the relevant elements and then update their HTML something more like this:
$(".infobox").next("td").html(function(i, h) { return h.split('<br>')[0] })

jQuery- How to select a element with class name from a list of elements

I am using jQuery.
I want to select a cell from a table.
So I tried the following codes.
// First line works fine for me. I can get a list of columns at the correct target row.
var targetColumns = $(elemClicked).closest("tr").find("td");
// I want to get the cell with the class named "draftstatus". This line has problem. I cannot get what I want.
var targetCell = columnsAtTargetRow.$(".draftstatus");
The targetColumns inspected from browser looks like the following:
The 5th td above is my target cell.
I also try to use find() function. It won't work either because find() will start from next children level.
columnsAtTargetRow.find(".draftstatus"); // this does not work.
What functions should I used to get that cell within that "list of td".
Thanks in advance.
You just need to figure out which selectors to use.
var targetColumns = $(elemClicked).closest("tr").find("td");
this goes up the DOM to the "tr" and selects the tds. If the elemClicked is inside a td you can select the tds with closest("td"), and then use siblings(".draftstatus");
If the elemClicked is a td, then you can just use siblings(".draftstatus");
Here is some example code to help demonstrate some selectors. Hope this helps some and not confused you more.
$(function(){
//reference all cells with myclass class using filter
$("#table1 tbody td").filter(".myclass").addClass("red");
// click events for all tds reference the .target class cell using siblings
$("#table1 tbody td").on("click",function(e){
$(this).siblings(".target").toggleClass("red");
});
//items inside a table cell click event
$("#table1 tbody td a").on("click",function(e){
//toggle bold class
$(this).closest("td").siblings(".target").toggleClass("bold");
//prevent event from bubbling up
e.stopPropagation();
});
})
.red {
background-color:red;
}
.bold { font-weight:bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" id="table1">
<tbody>
<tr>
<td>foo</td>
<td>bar</td>
<td class="myclass target">value2</td>
<td>Two link</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td class="myclass target">value2</td>
<td>Two link</td>
</tr>
</tbody>
</table>
This is incorrect:
columnsAtTargetRow.$(".myclass");
This should be:
columnsAtTargetRow.find(".myclass");

set tr background for td values

<table id="tab" border=2>
<tr> <td>1</td><td>a</td><td>red</td> </tr>
<tr> <td>2</td><td>a</td><td>green</td> </tr>
<tr> <td>3</td><td>a</td><td>orange</td> </tr>
<tr> <td>4</td><td>a</td><td>green</td> </tr>
<tr> <td>5</td><td>a</td><td>yellow</td> </tr>
<tr> <td>6</td><td>a</td><td>blue</td> </tr>
</table>
i can't modify html. i can use only jquery and css. i would like make:
if td == red then all TR with this TD is red, if td == green then all TR is green.
how can i make this?
live example: http://jsfiddle.net/sjuKa/1/
$('#tab tr').each(function() {
$(this).css({'background': $(this).children('td:last').text() });
});
example: http://jsfiddle.net/simoncereska/sjuKa/3/
You can use .text() to get the text value of a cell, and .parent() to get the element's parent. Combining these, you can loop the td tags, check if they contain 'red', and if so, get their .parent() and set its background-color to red.
See http://jsfiddle.net/sjuKa/2/ for a working example :)
JS:
var tds = $('td');
tds.each(function() {
$(this).parent().addClass( $(this).html().trim() );
})
CSS
.red
{
background-color: red;
}
JSFiddle
Same for all the rest - meaning CSS classes named: orange, green etc.
$(document).ready(function(){
$('table tr').each(function(){
if($(this).children(':last').text() == 'red') {
$(this).children('td').css('background-color', 'red');
}
})
})
fiddle here http://jsfiddle.net/sjuKa/1/

Categories

Resources