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!
Related
I've tried using the below js code to filter table rows. The code is originally from w3schools but I've done some modification to target all my input values. The filtering works great for one column but as fast as I try to input a value on a second column, it overwrites the previous filter.
For exampe if I filter for "Test" in column 1 it works great and hides the second row. If I after that also filter column 2 for id "2" it will hide the first row and instead display the second row for id 2. Is it possible to modify the code so that it only filters on the rows that are left and shown, not all the rows all together. Ive tried several hours trying to target only tr[i].style.display != "none"; but no success. My goal is something like this: DataTables. I've seen and read tons of other threads on here regarding this issue but nothing seems to work. Appreciate all the help and guidance.
Name
ID
Test
1
Another test
2
[Input field for filter]
[Input field for filter]
$(document).ready(function() {
document.querySelectorAll('.search').forEach(item => {
item.addEventListener('keyup', event => {
var input, filter, table, tr, td, i, txtValue;
input = event.target;
filter = input.value.toUpperCase();
table = document.getElementById("example");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[event.target.getAttribute('data-value')];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
})
})
} );
Your code was a mix of vanillaJS and jQuery, and tagged for both, so I went with jquery since it's a little more concise and easier to read.
Basically, you need to check both cells in each row against both search filters every time the key is pressed. To do so, I made things a tiny bit easier by giving the data TR rows a class so we're not searching the header or the cells with the search boxes. Then, I just compare filter 1 with cell 1 and filter 2 with cell 2 for each row. If there is a match for either, that row stays visible, otherwise it's hidden. I had to add in some logic in case there wasn't a value in either filter input.
Couple other notes:
$('.search').eq(0) is the same as the FIRST element with the class search
$(el).find('td').eq(0).text().trim().toLowerCase() is the same as find the FIRST TD tag's text, trim off the extra whitespace and convert to lowercase
$(document).ready(function() {
$('.search').keyup(function() {
let search1 = $('.search').eq(0).val().toLowerCase();
let search2 = $('.search').eq(1).val().toLowerCase();
$('.s-table tr.data').each(function(i, el) {
let val1 = $(el).find('td').eq(0).text().trim().toLowerCase()
let val2 = $(el).find('td').eq(1).text().trim().toLowerCase()
let ok = (search1 && val1.indexOf(search1) !== -1) || (search2 && val2.indexOf(search2) !== -1)
if (ok) $(el).closest('tr').show();
else $(el).closest('tr').hide();
})
return
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr class='data'>
<td>Test</td>
<td>1</td>
</tr>
<tr class='data'>
<td>Another test</td>
<td>2</td>
</tr>
<tr>
<td><input data-col='0' class='search' placeholder='filter'></td>
<td><input data-col='1' class='search' placeholder='filter'></td>
</tr>
</tbody>
</table>
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'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.
This is a function that, when passed a table as an argument, applies a different style color to alternating rows to improve readability. i.e. first row is dark grey, second row is light grow, third row is dark grey etc.
As mentioned, it gets passed the whole table as an argument. None of the rows have ids. Starting at this line var aTBODY = oTable.getElementsByTagName("tbody");, I understand what is happening. Namely, it gets the table body and then all the rows within it and stripes them alternately.
1) But what is happening exactly in the first five lines of the program? The comments don't explain it clearly for me.
2) does looping over a table length (i.e idArray.length) create an array of rows? what is happening with var id = idArray[indx]; ?
3) When it says, in the comments, get the table that corresponds to this id, using the code var oTable = document.getElementById(id) why is this a necessary step? what is happening?
thank you if you can explain
function createStripedTable(idArray) {
// for each table ID that we're given, stripe all the rows.
for (var indx = 0; indx < idArray.length; indx++) {
var id = idArray[indx];
// get the table that corresponds to this ID
var oTable = document.getElementById(id);
if (oTable == null)
return;
// get its table body, which contains all the TR tags
var aTBODY = oTable.getElementsByTagName("tbody");
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODY.length; i++) {
// get an array of all the TR tags in the TBODY
var aTR = aTBODY[i].getElementsByTagName("tr");
for (var j = 0; j < aTR.length; j++) {
// the % operator divides the given number by another
// and returns the remainder. This is how we alternate the
// rows.
aTR[j].className = (j % 2 == 1) ? "stripe1" : "stripe2";
}
}
}
}
Here's the code that's calling it.
function() {createStripedTable(new Array("MSFTQuotes"))
Here's an excerpt of the one and only one table that is passed.
<body>
<table id="MSFTQuotes">
<thead>
<tr>
<th colspan="7" align="center">
<span class="TableTitle">Stock Activity for Aug 5, 2008 - Nov 5, 2008 </span>
</th>
</tr>
<tr>
<th align="center" width="14%">
<div align="right" class="style5">
Date</div>
</th>
<th align="center" width="14%">
<div align="right" class="style5">
Open</div>
</th>
<th align="center" width="14%">
<div align="right" class="style5">
High</div>
</th>
<th align="center" width="14%">
<div align="right" class="style5">
Low</div>
</th>
<th align="center" width="14%">
<div align="right" class="style5">
Close</div>
</th>
<th align="center" width="14%">
<div align="right" class="style5">
Volume</div>
</th>
<th align="center" width="14%">
<div align="right" class="style5">
Adj Close</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td align="right">
5-Nov-08
</td>
<td align="right">
29.21
</td>
<td align="right">
29.36
</td>
<td align="right">
29.03
</td>
<td align="right">
29.31
</td>
<td align="right">
95,337,696
</td>
<td align="right">
29.31
</td>
The function accepts an array of id values corresponding to table elements. It loops through those IDs and does its striping work on all of the tbody elements within the tables.
Somewhat more annotated (see TJC:s):
function createStripedTable(idArray) {
// for each table ID that we're given, stripe all the rows.
// TJC: Loop through all of the IDs in the given array
for (var indx = 0; indx < idArray.length; indx++) {
// TJC: Get the ID value for index `indx` in the array
var id = idArray[indx];
// get the table that corresponds to this ID
var oTable = document.getElementById(id);
if (oTable == null) // TJC: Invalid ID, ignore it
return;
// get its table body, which contains all the TR tags
// TJC: Get the `tbody`s under the table. One table
// can have multiple `tbody` elements.
var aTBODY = oTable.getElementsByTagName("tbody");
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODY.length; i++) {
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var aTR = aTBODY[i].getElementsByTagName("tr");
for (var j = 0; j < aTR.length; j++) {
// the % operator divides the given number by another
// and returns the remainder. This is how we alternate the
// rows.
aTR[j].className = (j % 2 == 1) ? "stripe1" : "stripe2";
}
}
}
}
The good news is that IE9 finally supports the nth-child pseudo-class, so someday you'll be able to stop doing this with code.
idArray is an array of all IDS for more than one table. This function will change the alternate rows for each of the tables whose id is in idArray.
The outer loop is iterating through ids. The first five lines inside the loop are assuming they are ids of tables, and fetching the contents of the table element corresponding to each ID.
The next five lines in the loop then fetch the table body contents and change the css class of alternate rows.
Add these lines before the first for loop in the code
var tabarray=new Array();
tabarray.push(thetableidYoupassed);
idArray=tabArray
'thetableidYoupassed' is the actual argument with which you called the function 'createStripedTable'
Keep the rest of the code as it is...This should work fine...
Your method accepts an array of table IDs. So all the tables need to have IDs.
function createStripedTable(idArray) { //idArray is an array of table IDs
Then it loops through them and gets the ID one by one
for (var indx = 0; indx < idArray.length; indx++) {
var id = idArray[indx]; //this is the ID of a table
Then it checks whether the table actually exists in the DOM or not
var oTable = document.getElementById(id); //IF the table with a matching ID is not found, you get NULL
if (oTable == null)
return; //no table that matches the ID? return
Ideally, that line should be continue or something similar. Because in this instance. If you pass your method an array like ['table1', 'table2', 'faketable', 'table3'], your method won't strip table3 because it never gets there in the array (because of the return)
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>