onclick of cell css make that block yellow - javascript

.see js bin
if i drag on minute 15 to 45 then name john having csstdgreen then i have i to make john block yellow.
if i drag on minute 15 to 30 then jary having csstdgreen then i have i to make jary block yellow.
i drag on minute 15 then jack having csstdgreen then i have i to make jack block yellow.
only one at a time.How can i do that with jquery
i have shown an exmple here i have to do like this see demo
$(".csstdgreen").live('mousedown', function (e)
{
//This line gets the index of the first clicked row.
lastRow = $(this).closest("tr")[0].rowIndex;
$(this).removeClass("csstdgreen").addClass("csstdyellow");
e.preventDefault();
return false;
});
$(document).live('mouseup', function () { flag = false; });
$(".csstdgreen").live('mouseenter', function (e)
{
// Compares with the last and next row index.
currentRow = $(this).closest("tr")[0].rowIndex;
if (lastRow == currentRow || lastRow == currentRow - 1 || lastRow == currentRow + 1)
{
lastRow = $(this).closest("tr")[0].rowIndex;
} else
return;
if (flag)
{
$(this).children(":not(:first)").addClass("csstdyellow");
e.preventDefault();
flag = false;
}
});

So you are looking for something like this?
$('td').click(function() { // <-- on a td click
if ($(this).hasClass('csstdgreen')) { // <-- check if current clicked element has this class
$(this).css('background-color', 'yellow'); // <-- if it does the change background color
}
});​
Also don't forget to wrap your code inside a document.ready function so it waits for the dom to load before trying to look for your elements in the dom.
http://jsfiddle.net/64Byz/

i change your HTML because from your given HTML we can't achieve what you want...
i write javascript as
$(document).ready(function()
{
$('.csstdgreen').click(function(){
$('.csstdgreen').removeClass('csstdyellow');
$(this).closest('table').find('td').addClass("csstdyellow");
});
});
and your updated code with HTML is on
http://jsbin.com/icaluy/36/edit#source
and if you want to occur this on mouse over then follow this jsBin
http://jsbin.com/icaluy/37/edit#preview

your code is
<script type="text/javascript">
$(document).ready(function(){
$(".csstr").click(function(){
$(".csstr").removeClass('csstdyellow').addClass('csstdgreen');
var current_cls = $(this).attr('rel');
$('.' + current_cls + ' > td').removeClass('csstdgreen');
$('.' + current_cls).addClass('csstdyellow');
});
});
</script>
I made some changes your html to achieve this. I added the extra attribute "rel" and extra class to every row that we want to change. Its compulsion that "rel" value and added class name should be same. for example you want to change the color of all rows related with "john" then you have to add rel="cls1" and class="cls1" (if another class already added in row then add new class like class="csstr cls1") in every rows of john.
<table border="1">
<tr class="csstr cls1" rel="cls1" >
<td class="csstdgreen">
15
</td>
<td class="csstdgreen" rowspan="3">
john
</td>
</tr>
<tr class="csstr cls1" rel="cls1">
<td class="csstdgreen">
30
</td>
</tr>
<tr class="csstr cls1" rel="cls1">
<td class="csstdgreen ">
45
</td>
</tr>
<tr class="csstr cls2" rel="cls2">
<td class="csstdgreen ">15</td>
<td class="csstdgreen " rowspan="2">Jary</td>
</tr>
<tr class="csstr cls2" rel="cls2">
<td class="csstdgreen ">30</td>
</tr>
<tr class="csstr cls3" rel="cls3">
<td class="csstdgreen">15</td>
<td class="csstdgreen" rowspan="1">Jack</td>
</tr>
</table>

Related

td background colouring applied to complete column rather to a single cell

I've below html.
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
Below is the jquery I've written.
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')').text());
}
}); var idx2 = [];
for(var x=0;x<list2.length;x++){
if(list[x]===list2[x]){
//console.log(list[x]);
}else{
console.log('mismatched : '+list[x]);
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
idx2.push(x);
}
}
});
I'm trying to compare values in list with values in lqwasb02 column and if it finds the difference, it should highlight the background of td cell in red colour.
Current issue with jquery code, it is highlighting the complete column.
Can someone please help me where I'm getting wrong? If possible, please pass on the recommended solutions.
Many Thanks in advance.
The problem is that in your .find you are returning multiple elements that it's selector matches. So as opposed to storing the text value for your td elements in the second array, just store the actual td element, compare it's text, and then you can assign the background color directly to the element as opposed to finding it again via it's index:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
$.each(list,function(index,value){
//alert(index+' : '+value);
});
var idx;var list2 = new Array();
// Find index of cell with 'lqwasb02'
$('.myTable th').each(function(index) {
if ($(this).text() === 'lqwasb02') idx = index;
});
// Loop through each cell with the same index
$('.myTable tr').each(function() {
if($(this).find('td:eq('+idx+')').text() !=""){
list2.push($(this).find('td:eq('+idx+')')); // <-- Store the object here, not it's text value.
}
});
var idx2 = [];
for(var x=0; x < list2.length; x++){
if(list[x]===list2[x].text()) { // <-- compare list[x] to the text value of list2[x]
//console.log(list[x]);
} else {
list2[x].css("background-color", "red"); // <-- no find or selector needed, just apply it to the object you stored earlier.
};
idx2.push(x);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="myTable">
<tr>
<th class="cname">Component</th>
<th class="pname">Properties</th>
<th class="sname">lqwasb02</th>
</tr>
<tr>
<td class="cname">EMWBISConfig</td>
<td class="pname">reEvaluationTimer</td>
<td class="pvalue">every 1 hour without catch up</td>
</tr>
<tr>
<td class="cname">CalculateCategoryMediaInfoService</td>
<td class="pname">scheduled</td>
<td class="pvalue">yes</td>
</tr>
<tr>
<td class="cname">EMWBISScheduler</td>
<td class="pname">scheduled</td>
<td class="pvalue">no</td>
</tr>
<tr>
<td class="cname">CatalogTools</td>
<td class="pname">loggingDebug</td>
<td class="pvalue">false</td>
</tr>
</table>
$('.myTable tr').each(function() {
$(this).find('td:eq('+x+')').css("background-color", "red");
});
this piece of code assign a background colour to each cell of index 'x' for each rows (each cells of index x of each table rows represent a column).
You have to select only the rows which contains the cells you want to colour.
Here is how i would have approached solving this issue:
$(document).ready(function(){
var list = ['every 1 hour without catch up','yes','yes','false'];
var colIndex = findColIndex('lqwasb02');
// Loop over table rows
$('tr').each(function(){
// Look up cell with specific index
var $cell = $(this).find('td').eq(colIndex);
// Check if the text of the cell is not present in the list and do smth
if ($.inArray($cell.text(), list) === -1) {
$cell.css('background', 'red')
}
});
});
// helper function to find the index of column by text in the header
function findColIndex (headerText) {
var $col = $('.myTable th:contains(' + headerText + ')');
return $('.myTable th').index($col);
}
https://jsbin.com/fafegi/1/edit?js,output

How can I fix jquery when i change table elements to div style in body section?

<body>
<input type="text" id="search"/>
<table id="boxdata">
<tr>
<td class="namebox1">jQuery</td>
</tr>
<tr>
<td class="namebox2">javascript</td>
</tr>
<tr>
<td class="namebox3">php</td>
</tr>
<tr>
<td class="namebox4">sql</td>
</tr>
<tr>
<td class="namebox5">XML</td>
</tr>
<tr>
<td class="namebox6">ASP</td>
</tr>
</table>
</body>
<script>
$(document).ready(function(){
$('#search').keyup(function(){
searchBox($(this).val());
});
});
function searchBox(inputVal) {
$('#boxdata').find('tr').each(function(index, row){
var names = $(row).find('td');
var found = false;
if(names.length > 0) {
names.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()) & inputVal != ''){
found = true;
return false;
}
});
if(found == true)
$(row).addClass("red");
else
$(row).removeClass("red");
}
});
}
</script>
there's a textfield for searching words and there are 6 words in the each 6 boxes below textfield.(I omitted css codes. but, it wouldnt matter to solve the problem.). if i type a letter 's' then the words that including letter 's' like 'javascript', 'sql', 'ASP' these font-color will be changed black to red. And i made it by using table elements in html but i'd like to change all elements into div style to put some data fluidly later. i have difficulty to fix especially jquery. how can i fix it?
You can simplify this a little bit.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal, 'i');
$('#boxdata').find('tr').removeClass('red').filter(function() {
return $(this).find('td').filter(function() {
return regExp.test( $(this).text() );
}).length && $.trim(inputVal).length;
}).addClass('red');
}
So remove the red class from all <tr>'s first, then filter them, test the text of each <td>, if it matches, return the <tr> and then add the class red again.
Here's a fiddle
As for changing from a table to div, the jQuery would depend on how you structure your markup, but the principle would remain the same.
Here's another fiddle
You can make javascript code HTML agnostic by using css classes instead of element names. Demo.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal = $.trim(inputVal), 'i'),
highlight = 'red';
$('#wrapper').find('.word') //instead of tr/td/div
.removeClass(highlight)
.each(function(){
var $this = $(this);
inputVal && regExp.test($this.text()) &&
$this.addClass(highlight);
});
}

Compare text inside custom attribute

I've a long table made of rows like this
<tr id="row_369696" class="lvtColData" bgcolor="white" onmouseout="this.className='lvtColData'" onmouseover="this.className='lvtColDataHover'">
<td width="2%"></td>
<td bgcolor="#FFFFFF">
27-10-2014
<span style="display:none;" module="Accounts" fieldname="cf_1390" recordid="369696" type="metainfo"></span>
</td>
<td bgcolor="#FFFFFF">
12:30
<span style="display:none;" module="Accounts" fieldname="cf_1380" recordid="369696" type="metainfo"></span>
</td>
</tr>
the end result that i need is to change the background of this row when the time and the date match the content of the columns marked by the fieldname cf_1390 for the date part and the cf_1380 for the time part.
i was thinking of using jquery to cycle trough rows, find the content of the cell, compare it to now date, and if it matches change the row background, but i cannot figure out how to do it.
can someone help me with some jsfiddle example ? :)
Here is an example of looping through your rows, checking if the date & time match the variables (Which i've just hard coded at the top for this example) - and then setting them to red if it finds both a date & a time match in that row.
JS:
var date = "27-10-2014";
var time = "12:32";
$(document).ready(function(){
$('#targetTable tr').each(function(i,e){
var match = 0;
$(this).children('td').each(function(i2,e2){
content = $(e2).html().substring(0, $(e2).html().indexOf('<span')).trim();
if(content == date){ match++; }
if(content == time){ match++; }
});
if(match == 2){
$(this).css('background','red');
$(this).children('td').css('background','red');
}
});
});
Fiddle
Here is an easy-to-understand example.
JSFiddle http://jsfiddle.net/h3Xd3/
HTML
<table id="myTable">
<tr id="row_369696" >
<td bgcolor="#FFFFFF">
27-10-2014
<span style="display:none;" module="Accounts" fieldname="cf_1390" recordid="369696" type="metainfo"></span>
</td>
<td bgcolor="#FFFFFF">
12:30
<span style="display:none;" module="Accounts" fieldname="cf_1380" recordid="369696" type="metainfo"></span>
</td>
</tr>
</table>
CSS .highlight{background-color:lightgrey;}
JQUery
function datesEqual(a, b)
{
return (!(a>b || b>a))
}
$(function () {
// Handler for .ready() called.
$("#myTable tr").each(function(){
//Get date and hour. Split each item by the appropriate separator
var date_row = $(this).find("td:eq(0)").text().split("-");
var hour_row = $(this).find("td:eq(1)").text().split(":");
var date_object = new Date(date_row[2], date_row[1] - 1, date_row[0], hour_row[0], hour_row[1]);
var YOUR_OTHER_DATE = new Date(date_row[2], date_row[1] - 1, date_row[0], hour_row[0], hour_row[1]); //You have to change this line
if ( datesEqual(YOUR_OTHER_DATE, date_object) == true){
$(this).find("td").addClass("highlight");
}
});
});
Don't forget to change the YOUR_OTHER_DATE value. It depends to your need but we don't have enough details to give a complete answer.

How to put an onclick event for a HTML table row created dynamically through java script.?

I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.

How to get <td> value in textbox

I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery
If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />​
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});​
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/
You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});

Categories

Resources