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.
Related
I'm a beginner at JavaScript and haven't been able to figure this out...
I need to check each row of a table to see if the string "Business Cards" exists in each row. If EVERY row contains this string, I'll proceed with option A, but if even one row doesn't contain the string, I'll stop checking and proceed with option B.
Here is an idea of what the table looks like in HTML (although the number of rows and products in each row will vary, since they're dynamically generated):
<table class="rgMasterTable" border="0" id="ctl00_cphMainContent_dgShippingItems_ctl00" style="width:100%;table-layout:auto;empty-cells:show;">
<thead>
<tr>
<th scope="col" class="rgHeader" style="text-align:center;">Name</th>
<th scope="col" class="rgHeader" style="text-align:center;">No. of Units</th>
</tr>
</thead>
<tbody>
<tr class="rgRow" id="ctl00_cphMainContent_dgShippingItems_ctl00__0" style="text-align:center;">
<td style="width:250px;">
Business Cards - TEST - CA Back
</td>
<td style="width:100px;">
250 Business Cards
</td>
</tr>
<tr class="rgAltRow" id="ctl00_cphMainContent_dgShippingItems_ctl00__1" style="text-align:center;">
<td style="width:250px;">
Business Cards - Joint Venture - TEST
</td>
<td style="width:100px;">
250 Business Cards
</td>
</tr>
</tbody>
</table>
And here's my attempt at the code. I'm trying to make use of the fact that the tr id will always have the index (eg: "ctl00_cphMainContent_dgShippingItems_ctl00__0" for the first row, "ctl00_cphMainContent_dgShippingItems_ctl00__1" for the second, etc), but maybe there's an easier way to do this?
var businessCardItem = 'Business Cards';
var orderItemCount = $('#ctl00_cphMainContent_dgShippingItems_ctl00 tr').length;
var onlyBusinessCards = true;
for (var i = 0; i <= orderItemCount; i++) {
if($('#ctl00_cphMainContent_dgShippingItems_ctl00__' + i).text().indexOf(businessCardItem) >= 0) {
return onlyBusinessCards;
}
else {
onlyBusinessCards = false;
return onlyBusinessCards;
break;
}
}
if (onlyBusinessCards == true) {
//Option A
}
else {
//Option B
}
Any help would be appreciated! Let me know if any more detail or clarification is needed!
Count how many rows contain "Business Cards" and compare to the number of rows:
Note: only count rows within tbody
var table = $("#ctl00_cphMainContent_dgShippingItems_ctl00");
var rows = $("tbody tr",table).length;
var rowsWithBC = $("tbody tr:contains(Business Cards)",table).length;
if( rows == rowsWithBC ) {
// Option A
} else {
// Option B
}
I have a table in which I display in the first line the current month
and I want to change the number of td in the second line whith ng-click function.
(if I click into a next button I get the next month and the number of td in the second tr become exactly the number of the day of this month(next month)
what I ve done :
$scope.nextMonth=function(month){
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var numMonth = months.indexOf(month);
console.log(numMonth);
if(numMois == 11){
$scope.month= months[0];
}
else {
$scope.month=months[numMonth+1];
}
$scope.nbrJrs = NbJourByMonth(numMonth,2016);
};
This is a screenshot of what I actually have :
Edit
and when I click next button I get this :
As you can see the month change but the number of td which refers to the number of day in the month doesn't change !! :(
In the view i have this :
<table>
<thead>
<th><a href="#" onclick="previousMonth()"><</th>
<th class="col-md-4" colspan="{{NbJourByMonth(m,year)-2}}"><center>{{month}}</center></th>
<th><a href="#" onclick="nextMonth()">></th>
</thead>
<tbody>
<td id="{{$index+1}}" ng-repeat="n in range(nbrJrs)">{{$index+1}}</td>
</tbody>
</table>
and this is the range function :
$scope.range = function (count) {
var ratings = [];
for (var i = 0; i < count; i++) {
ratings.push(i)
}
return ratings;
}
When I click into next flech I can change the name of the month and also I get the number of day in this month but the number of td doesn't change (I get 31 td I don't know how I can redraw the table.)
Can someone help me please ?
#Akino
One option, you could make the colspan of the TH to be (number of days in a month) -2 and bind that dynamically using Angular.
<table>
<th><!- Placeholder for Left Nav Button --></th>
<th colspan="{{currentMonthDays-2}}">{{currentMonth}}</th>
<th><!- Placeholder for Right Nav Button --></th>
<tr>
<td id="{{$index+1}}" ng-repeat="n in range(nbrJrs)">{{$index+1}}</td>
</tr>
</table>
Hope this helps!
<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);
});
}
.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>
I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>