How to set contents to background color? - javascript

I have a table with a variety of dynamically generated background colors. I'd like to use jQuery to populate the table cell contents with the cell's actual background color. I can use $("td").text("new contents"); to change the contents of the cells. I tried $("td").text($(this).css("backgroundColor")); to put the background color into the cell, but the background color doesn't come through.
$("td").text(
$(this).css("backgroundColor")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>lighten</td>
<td style="background-color: #d379a6;">10%</td>
<td style="background-color: white;">50%</td>
<td style="background-color: white;">100%</td>
</tr>
<tr>
<td>darken</td>
<td style="background-color: #ad3972;">10%</td>
<td style="background-color: #14060d;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
<tr>
<td>mix</td>
<td style="background-color: #b24a7e;">10%</td>
<td style="background-color: #632946;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
</table>

Try this instead:
$("td").text(function() {
return $(this).css("backgroundColor");
});
.text method can take a function as argument. In this case this function must return value to be used as new text content for elements in collection.
Your version $("td").text($(this).css("backgroundColor")); is incorrect because in this case this points to global object (which is window object) and obviously $(this).css("backgroundColor") returns nothing.
$("td").text(function() {
return $(this).css("backgroundColor");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>lighten</td>
<td style="background-color: #d379a6;">10%</td>
<td style="background-color: white;">50%</td>
<td style="background-color: white;">100%</td>
</tr>
<tr>
<td>darken</td>
<td style="background-color: #ad3972;">10%</td>
<td style="background-color: #14060d;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
<tr>
<td>mix</td>
<td style="background-color: #b24a7e;">10%</td>
<td style="background-color: #632946;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
</table>

The accepted answer solved the problem I was having, but I also wanted the colors to be displayed in hex, which isn't what was returned by jQuery. So I ported in a solution for that from Can I force jQuery.css("backgroundColor") returns on hexadecimal format?. This is the final jQuery I ended up implementing:
$("td").text(function() {
color = $(this).css("backgroundColor");
bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
});

Related

How do I display the content of closest <td> on javascript?

I have looked everywhere, but my code does not work at all. I simply want to display the content of the td I'm clicking on.
I have this table:
<tr class='rowData' tooltip='{caracteristicas}'>
<td nowrap class='Body'><a href='{caracteristicas}' target="_blank" style="color:black" onClick='return confirm("VOCÊ SERÁ REDIRECIONADO PARA:\r\r {caracteristicas}")'>{inputDescItem}</a></td>
<td nowrap class='Body' align='right'>{quantidade} {hiddenCodigoItem}</td>
<td nowrap class='Body' align='center'>{grupoEstoque}</td>
<td nowrap class='Body' align='center'>{inputCodigoItem}</td>
<td nowrap class='Body' align='center'>{btnAtualizaItem}</td>
<td nowrap class='Body' align='center'><button type="button" class="btnTest">Assign</button></td>
<td nowrap class='Body' align='center' class="testNameClass" name="output" style="display:none;">{caracteristicas}</td>
</tr>
I want it so that when I click on the CLICK ME tag, it will display (in a pop-up, alert, modal or anything) the content of the below tag (that I'm not displaying).
I have the following javascript:
$("btnTest").on("click", function() {
alert($(this).closest('tr').find('testNameClass').val());
});
I'm not very good at JS so please go easy on me.
Look like you missing
$(".btnTest") instead of $("btnTest")
and just try
$(".btnTest").on("click", function() {
alert($(this).parents('tr').find('.testNameClass').val());
});
To target specific elements using a class you need to use a dot in front of the class name. In your case .btnTest and .testNameClass.
$(".btnTest").on("click", function() {
alert($(this).closest('tr').find('.testNameClass').text());
});
As you are looking for the text inside the td element you should use .text() instead of .val()
In the below example column ent_3 is hidden and you will get its values using the script mentioned above.
$(".btnTest").on("click", function() {
alert($(this).closest('tr').find('.testNameClass').text());
});
.testNameClass {
display: none;
}
table {
border-collapse: collapse;
}
th, td { border: 1px solid #000; padding: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dataTable">
<thead>
<tr>
<th>pk</th>
<th>ent_1</th>
<th>ent_2</th>
<th>ent_3</th>
</tr>
</thead>
<tbody>
<tr>
<td>PK Row 0</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 0 Ent_3</td>
</tr>
<tr>
<td>PK Row 1</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 1 Ent_3</td>
</tr>
<tr>
<td>PK Row 2</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 2 Ent_3</td>
</tr>
</tbody>
</table>
Your method will be handed a reference to the MouseEvent which represents details of the click. Since it is an Event, it has a currentTarget which represents an "element" in the so-called DOM ... an internal data-structure which represents the HTML. This data structure is in the form of a tree, where each node has one parent, two siblings, and some children. You can now write code to "walk up the tree" until you encounter a td node. The first one you come to is the innermost containing td.
I think you are targeting is incorrect use a . before the class name - also I see two classes in one element I set this up for you here have a look
https://jsfiddle.net/hw0ansyj/1/
$(".btnTest").on("click", function() {
alert($('.testNameClass').html());
});

Unable to save input data from HTML table cells into JavaScript variables

I have tried to put input from a user into cells of a table, which was created using HTML and to save that data into a variable of JavaScript.
I was trying to get the data from rows cell of table to JavaScript variables one by one, but I'm getting undefined in place of data when alerting the data after summit.
HTML code
<table border = "2" cellpadding = "6" cellspacing = "6" bordercolor = "white" bgcolor = "red" class="center" id="mytable" >
<tr>
<th style="background: white;">EDUCATION</th>
<th style="background: white;">INSTITUTE</th>
<th style="background: white;">PERCENTAGE</th>
</tr>
<tr>
<td style="color: white;">10 th</td>
<td id="10inst"><input type="text"></td>
<td id="10per"><input type="text"></td>
</tr>
<tr>
<td style="color: white;" >12 th</td>
<td id="12inst"><input type="text"></td>
<td id="12per"><input type="text"></td>
</tr>
<tr>
<td style="color: white;">Graduaction</td>
<td id="gradinst"><input type="text"></td>
<td id="gradper"><input type="text"></td>
</tr>
<tr>
<td style="color: white;">Masters</td>
<td id="masterinst"><input type="text"></td>
<td id="masterper"><input type="text"></td>
</tr>
</table><br><br>
JavaScript code
var inst10 = document.getElementById("mytable").value;
var inst12 = document.getElementById("12inst").value;
var masterinst = document.getElementById("masterinst").value;
var per10 = document.getElementById("10per").value;
var per12 = document.getElementById("12per").value;
var masterper = document.getElementById("masterper").value;
var gradinst=document.getElementById("gradinst").value;
var gradper=document.getElementById("gradper").value;
There might be 2 problems in your code:
Make sure you run your JavaScript only after you enter text in the input elements.
You have <input> element inside <td> element. It means that when you getElementById of the <td> - you are not yet referencing the '' element. And the .value of '' is really undefined. So to fix that:
instead of
var inst12 = document.getElementById("12inst").value;
do:
var inst12 = document.getElementById("12inst").childNodes[0].value;
Full working example: https://jsfiddle.net/1dpg5j3q/
You must be add "id" attribute in input elements, not td elements or table elements
Like this;
<input id="12inst" type="text">

Calculating Number IDs

I wasn't quite sure how to word this in the title, so thank you for clicking to on this.
So now to my problem:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
.block {
background-color: black;
}
</style>
<table border='1px'>
<tr>
<td id='11'></td>
<td id='12'></td>
<td id='13'></td>
<td id='14'></td>
<td id='15'></td>
</tr>
<tr>
<td id='21'></td>
<td id='22'></td>
<td id='23'></td>
<td id='24'></td>
<td id='25'></td>
</tr>
<tr>
<td id='31'></td>
<td id='32'></td>
<td id='33' class="block"></td>
<td id='34'></td>
<td id='35'></td>
</tr>
<tr>
<td id='41'></td>
<td id='42'></td>
<td id='43'></td>
<td id='44'></td>
<td id='45'></td>
</tr>
<tr>
<td id='51'></td>
<td id='52'></td>
<td id='53'></td>
<td id='54'></td>
<td id='55'></td>
</tr>
</table>
<button onclick="blockUp()">Up</button>
<button onclick="blockDown()">Down</button>
<button onclick="blockLeft()">Left</button>
<button onclick="blockRight()">Right</button>
<script>
var blockUp = function() {
var oldBlock = document.getElementsByClassName("block")[0].id;
var newBlock = Math.floor(oldBlock + 1);
document.getElementById(newBlock).classList.add("block");
document.getElementById(oldBlock).classList.remove("block");
}
</script>
</body>
</html>
This code is not complete, as I want to fix this problem first.
I want to use Math.floor to get a certain ID (thus, IDs as numbers), and manipulate them. More specifically, I want to find the ID of the cell that currently has the .block class, find the ID of the cell above that using Math.floor(oldBlock + 1), remove the class from the original cell, and add the class to the new cell. I used variables so that the function would always be able to run, rather than making a million if/else if/else statements.
Unfortunately, this doesn't work with my current code. How would I be able to do this?
Any help is appreciated!
You have to make sure that "oldBlock" contains a number before trying to do math with it (like adding 1):
var oldBlock = +document.getElementsByClassName("block")[0].id;
That's one way of doing it. You could also use parseInt():
var oldBlock = parseInt(document.getElementsByClassName("block")[0].id, 10);
The value of the "id" property will be a string, so if you involve that in an addition operation JavaScript will treat it as string concatenation. By forcing it to be a number first, you'll get the effect you want.

Changing background color onclick

I dont know if it is possible to do but i this is my code.
function start(blauw){
document.getElementById(blauw).style.background="white";
}
<table>
<tr>
<td id= niks></td>
<td id= niks></td>
<td id= blauw onclick="start(id)">1</td>
<td id= blauw onclick="start(id)">2</td>
<td id= blauw>3</td>
<td id= blauw>4</td>
<td id= blauw>5</td>
<td id= blauw>6</td>
<td id= blauw>7</td>
<td id= blauw>8</td>
<td id= niks></td>
<td id= niks></td>
</tr>
</table>
i want to achieve that if i click on it the background will turn into white so people now what they are booking. but do i have to give everything an own ID? because right now if i click on "2" only "1" turns white and "2" won't turn white.
(excuse me for my bad english)
Instead of passing attributes just pass the element itselfe:
function start(element) {
element.style.background = "green";
}
<table>
<tr>
<td class=niks></td>
<td class=niks></td>
<td class=blauw onclick="start(this)">1</td>
<td class=blauw onclick="start(this)">2</td>
<td class=blauw>3</td>
<td class=blauw>4</td>
<td class=blauw>5</td>
<td class=blauw>6</td>
<td class=blauw>7</td>
<td class=blauw>8</td>
<td class=niks></td>
<td class=niks></td>
</tr>
</table>
And as mentioned in the comments - ID`s had to be unique!!
EDIT:
Altered function to switch the background color.
function start(element) {
var backgroundColor = element.style.background;
if (backgroundColor === "green") {
element.style.background = "red";
} else {
element.style.background = "green";
}
}
So this is a very simple demo
See FIDDLE

Jquery Javascript function, simple error, can't find it!

When my page loads it calls the function like below:
<body onLoad='changeTDNodes()'>
And the code it calls is below:
enter code here
<script src='jquery-1.4.2.min.js' type='text/javascript'></script>
<script>
function changeTDNodes() {
var threshValue = 10;
$(".threshold").each(function(elem) {
if($("b",elem).innerText > threshValue) {
elem.addClass("overThreshold");
}
});
});
}
I have the class setup correctly in CSS
.overThreshold {
td{font-size:72px;}
th{font-size:72px;}
}
But no classes are being changed, whats going on?
Thanks for all your help!
Below is whole page:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html>
<head>
<title>Livermore Readerboard</title>
<script src='jquery-1.4.2.min.js' type='text/javascript'></script>
<script>
$(function() {
var threshValue = 10;
$(".threshold").each(function(elem) {
if($("b",elem).innerText > threshValue) {
elem.addClass("overThreshold");
}
});
});
</script>
<style type='text/css'>
#InnerRight {
width: 50% !important;
position: relative !important;
float: left !important;
}
#InnerLeft {
width: 49% !important;
position: relative !important;
float: right !important;
}
.overThreshold {
td{font-size:72px;}
th{font-size:72px;}
}
</style>
</head>
<body>
<div id='InnerLeft'>
<table border=1 cellpading=1 cellspacing=0>
<tr align=right>
<td align=left><b>Split/Skill</b></td>
<td align=center><B>CIQ</b></td>
<td align=center><b>EWT</b></td>
<td align=center><b>Agents Staffed</b></td>
<td align=center><b>Avail</b></td>
</tr>
<tr align=right>
<td align=left><b>LEAD_IP_REP_video</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>:00</b></td>
<td align=center><b>3</b></td>
<td align=center><b>2</b></td>
</tr>
<tr align=right>
<td align=left><b>LEAD_IP_REP_tier</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>:00</b></td>
<td align=center><b>3</b></td>
<td align=center><b>2</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_video</b></td>
<td align=center class='threshold'><B>60</b></td>
<td align=center><b>10:12</b></td>
<td align=center><b>58</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_hsi</b></td>
<td align=center class='threshold'><B>34</b></td>
<td align=center><b>18:15</b></td>
<td align=center><b>56</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_hn</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>3:48</b></td>
<td align=center><b>3</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_cdv</b></td>
<td align=center class='threshold'><B>6</b></td>
<td align=center><b>14:53</b></td>
<td align=center><b>56</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>CommOps FieldCare</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>0</b></td>
<td align=center><b>0</b></td>
<td align=center><b>0</b></td>
</tr>
</table>
</div>
</body>
</html>
You would be far better off, if possible, using ids on your elements, and then using document.getElementById() (or, better yet, using Dojo, MooTools or JQuery to make your code simpler).
So your html looks like:
<td id="cell-repair-video">Repair value is <b>23</b></td>
<td id="cell-ppv">PPV value is <b>5</b></td>
Then your JavaScript looks like:
var RepairVideo_cell = document.getElementById("cell-repair-video");
var RepairVideo_value = RepairVideo_cell.getElementsByTagName("b")[0];
In JQuery (and others), you can easily use a class to determine which elements need thresholding
In this case, your html looks like:
<td class="threshold">Repair value is <b>23</b></td>
<td class="threshold">PPV value is <b>5</b></td>
And your entire JavaScript looks like:
$(function() {
var threshValue = 10;
$('.threshold').each(function(index) {
var thisValue = parseFloat( $('b', this).text() );
if(thisValue > threshValue) {
$(this).addClass('overThreshold');
}
});
});
In your current example, there is an error in your CSS
To style td and th elements with a classname, go
td.overThreshold, th.overThreshold {
background: #F00; /* for example */
}
Presumably you are passing through something to the applyThresholds function where innerHTML on myvalue is not valid. Does it work ok in firefox etc?
My guess would be that the crazy document.getElementsByTagName('B')[36]; code is just returning undefined at some point. You should put some code in applyThresholds to check to see if you are getting invalid arguments through. Something like:
if(myvalue == null || mycell == null) {
return;
}

Categories