I have a table that contains dates within one table cell on each row. I use Javascript to detect today's date, and if the dates in the cell are before today's date, I remove the whole table row.
$(function(){
$('.table-cell-containing-date').each(function(key,value){
var currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
var date = new Date($(value).text());
if(date < currentDate){
$(value).parent().remove();
}
});
});
I'm trying to amend this so that once all dates in the table for a particular month are in the past (and therefore removed), the whole table itself should be removed.
I don't even know where to start to be honest. I need to check the whole table to see if any rows in each table exist after the above Javascript has fired, and if they don't, remove the whole table.
I've setup a Fiddle where you will see the first row being removed because the date is in the past. https://jsfiddle.net/67ktea40/1/
Many thanks in advance,
J
Add the two line as below
$(function(){
$('.production-date').each(function(key,value){
var currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
var date = new Date($(value).text());
if(date < currentDate){
$(value).parent().remove();
var count = $('.tour-dates-table tr').length;
if(count<=2) $('.tour-dates-table').remove();
}
});
});
Updated version of answer for your question
$(function(){
$('.production-date').each(function(key,value){
var currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
var date = new Date($(value).text());
if(date < currentDate){
var currenttable = $(value).parent().closest('table');
$(value).parent().remove();
var count = $(currenttable).children('tr').length;
if(count<=2) { $(currenttable).remove(); }
}
});
});
Check if it's empty and them remove it
function deleteIfEmpty() {
var tbody = $("table tbody");
if (tbody.children().length == 0) {
$("table").remove();
}
}
And call it after every row-removal.
Check if table has no tr then remove it
if (!$('table').find('tr').length){
$('table').remove();
}
You can check the table .has() no production-date element, then remove entire table.
var table = $('table.tour-dates-table');
if (table.has(".production-date").length == 0) {
table.remove();
}
In DEMO, as I have removed all tr containing .production-date
First bind an event to the table's container div.And then check for table rows length.If its zero remove the table.:
$('#container-div').on('DOMSubtreeModified', function(){
if($('#myTable tr').length==0){
$('#myTable').remove();
}
});
Related
I am looking for a way to make each td in the datepicker unique. I have set a price under each highlighted date but the problem is that the price is the same on every date.
addCustomInformation : function(x) {
window.bookingRequest.totalPrice = 0;
window.bookingRequest.totalAccommodationOnlyPrice = 0;
window.rateTableRowIndex = 0;
var selectedTimeFrom = x;
var selectedTimeTo = x + 604800000;
while (selectedTimeFrom < selectedTimeTo) {
accommodations.buildRateRow(selectedTimeFrom, 1, 0, 3);
selectedTimeFrom += (86400000 * 7);
}
var price = accommodations.formatPrice(window.bookingRequest.totalAccommodationOnlyPrice);
var newprice = price.substring(3);
setTimeout(function() {
$(".ui-datepicker-calendar td").filter(function() {
var date = $(this).text();
return /\d/.test(date);
}).find("a").attr('data-custom', newprice); // Add custom data here
}, 0)
}
This code fetches the price but the price is assigned to ".ui-datepicker-calendar td" which it should not. I want it to add the price to the current td in the calendar loop. The addCustomInformation function run on every highlighted td.
My thought was to add the date as a class for each td so it would look something like this
<td class="05-08-2016 dp-highlight"></td>
<td class="06-08-2016 dp-highlight"></td>
Can not figure out how to do this. If it can be done I could send the current date in the loop as a parameter to the function and add the price to the correct td.
I can not use return in "beforeShowDay" because this is used to return the different classes for highlighted and disabled dates. Adding the class in a current return like return [true, 'dp-highlight current-date'] is also not possible as I can not run the addCustomInformation function after the return.
x in the function is the current date in miliseconds used to calculate the price.
Any other solution would also be welcome.
Michael
In the datepicker file i managed to get a id added to each active/clickable td in the calendar. My custom function now looks like this:
addCustomInformation : function(currentday, dateclass) {
window.bookingRequest.totalAccommodationOnlyPrice = 0;
window.rateTableRowIndex = 0;
var selectedTimeFrom = currentday;
var selectedTimeTo = currentday + 604800000 // the day one week from current day ;
while (selectedTimeFrom < selectedTimeTo) {
accommodations.buildRateRow(selectedTimeFrom, 1, 0, 3);
selectedTimeFrom += (86400000 * 7);
}
var price = accommodations.formatPrice(window.bookingRequest.totalAccommodationOnlyPrice);
var newprice = price.substring(4) // remove DKK from price;
setTimeout(function() {
$("." + dateclass).text('DKK ' + newprice) // add the price to the td;
},1000)
Take a look at this page http://designunivers.dk/green2green/hotel/hotel-isla-canela-golf/ and chose the tab "Priser og bestilling". Next press the "Vælg datoer" button in fx "Billund - Sevilla". In the calendar go to the months february, march, april. Sometimes the price shows DKK 0 and other times it shows the correct price. If you refresh the page and try again it shows the price on some of the dates that returned DKK 0 before. Totally weird.
Any ideas on the problem? Is it because the "newprice" variable is not yet calculated before I add it to the td field? Any solutions on this in such case?
Currently I am working with jquery clone and calculating from date and to date displaying in the top of the panel using date picker. With my curernt code I am able to clone the row and add the two date values but when I click the delete button it is deleting the cloned row but it is not updating the total result label in the top of my example.
Here is my code for delete button:
$(document).on('click', ".btn_less1", function() {
var len = $('.cloned-row3').length;
if (len > 1) {
var RemoveStartDate = $(this).closest(".btn_less1").parent().parent().parent().find('.startDate ').val();
var RemoveEndDate = $(this).closest(".btn_less1").parent().parent().parent().find('.endDate ').val();
if ((RemoveStartDate != '') || (RemoveEndDate != '')) {
var dateStartArray = RemoveStartDate.split('/'),
dateEndArray = RemoveEndDate.split('/');
var fromdate = new Date(dateStartArray[2], dateStartArray[0] - 1, dateStartArray[0]),
todate = new Date(dateEndArray[2], dateEndArray[0] - 1, dateEndArray[0]);
var yearsDifference = todate.getFullYear() - fromdate.getFullYear();
var monthsDifference = (todate.getMonth() + 12 * todate.getFullYear()) - (fromdate.getMonth() + 12 * fromdate.getFullYear());
var PrevTotalYear = parseInt($("#txt_expy>span").text());
var PrevTotalMonth = parseInt($("#txt_expm>span").text());
$("#txt_expy>span").text('');
$("#txt_expm>span").text('');
PrevTotalYear = PrevTotalYear * 12;
var CurTotalYear = Math.floor(((PrevTotalYear + PrevTotalMonth) - monthsDifference) / 12);
var CurTotalMonth = (monthsDifference - PrevTotalMonth) % 12;
$("#txt_expy>span").text(CurTotalYear);
$("#txt_expm>span").text(CurTotalMonth);
$(this).closest(".btn_less1").parent().parent().parent().remove();
} else {
$(this).closest(".btn_less1").parent().parent().parent().remove();
}
}
});
When the user selects from date as 12/01/2000 and to date as 12/01/2003
the result will be Total work experience 3Years 0Month
and if the user clicks add more button it will create one more row
and again from date as 12/01/2004 and to date as 12/01/2015
the result will be Total work experience 15Years 0Months with my code. This works as I would expect it.
When the user clicks the delete button it is deleting the row but it is not updating the Total work experience and if I click add more button if I try to modify the previous from date and to date it is not updating in the result either.
Here is the fiddle link
Thanks in advance
Your problem is the original HTML starts like this:
<label class="years_lab" id="txt_expy"><span>0</span>Years</label>
When the values are changed you set the value like this:
document.getElementById("txt_expy").innerHTML
Which sets the inside of the label and removes the span element. And when you try to recalculate the total you select it like this:
$("#txt_expy>span")
But this returns an empty jQuery object since the span doesn't exist anymore.
Fiddle: http://jsfiddle.net/bqgjro6d/41/
I changed the last two lines from:
document.getElementById("txt_expy").innerHTML = diffYears;
document.getElementById("txt_expm").innerHTML = diffMonths;
To:
$("#txt_expy>span").text(diffYears);
$("#txt_expm>span").text(diffMonths);
I have a form where i can select a product then set a begin week (for example 1) and a end week (for example 10)
Then i have a table with 52 rows that represent the weeks. I want when a user selects a product and set the weeks it adds the product in the table on the set weeks.
Everything works fine when i add week 1 - 10 but when i put 3 - 10 it doesnt work.
Here is my Jquery code
$(".sub_product_toevoegen").click(function(e) {
e.preventDefault();
var product = $("select[name='select_product'] option:selected").val();
var start_week = $("input[name='start_week']").val();
var eind_week = $("input[name='eind_week']").val();
$(".tabs .nieuwe_offerte_table tbody tr td a.product_toevoegen").each(function(index) {
for (i = start_week; i <= eind_week; i++) {
if (i == index + 1) {
$(this).append(product);
}
}
});
});
Someone can tell me what im doing wrong ?
Try changing famous each function to this:
$(".tabs .nieuwe_offerte_table tbody tr td a.product_toevoegen").slice(start_week-1, eind_week).append(product);
I have a sharepoint discussion list. There's a field called "Last Updated". I'm trying to highlight rows where last updated is greater than 1 hour.
This is what I'm currently trying:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https:////cdnjs.cloudflare.com/ajax/libs/moment.js/2.6.0/moment.min.js"></script>
<script>
$(document).ready(function(){
var now = moment().format('l h:mm:ss a');
console.log(now);
//$row = $("td .ms-vb2:contains('6/13/2014 9:46 AM')");
$rows = $("td[id$='WPQ3'] .ms-vb2:contains('AM'), td[id$='WPQ3'] .ms-vb2:contains('PM')");
console.log($rows);
$times = $rows.children
$rows.parent().css("background-color", "rgba(203, 231, 57, 0.37)");
});
</script>
</head>
</html>
Right now, every cell is highlighted based on my selector.
$rows contains 2 objects and the innerText for both objects contains the time, so something like "6/13/2014 9:46 AM".
I'm not sure how to look at the time for each row, compare it with the now variable and then highlight if my condition is met, which is "Highlight if less than 1 hour difference"
I was able to solve this using moment.js and a bit more research into jQuery.
Here's my solution:
$(document).ready(function(){
//STORE CURRENT TIME
var now = moment()
//GET ALL ROWS I'M TRYING TO HIGHLIGHT
$rows = $("td[id$='WPQ3'] .ms-vb2:contains('AM'), td[id$='WPQ3'] .ms-vb2:contains('PM')");
//GO THROUGH EACH ROW FOUND
$.each($rows, function (index, row){
//FOR EACH ROW CONVERT TIME INTO MOMEMTJS OBJECT
var lastUpdateTime = moment(row.innerText)
//USING MOMENT JS, FIND THE DIFFERENCE BETWEEN LAST UPDATE AND NOW
var difference = now.diff(lastUpdateTime, 'hours');
//IF THE DIFFERENCE IS LESS THAN AN HOUR HIGHLIGHT THE CURRENT ROWA
if(difference <= 1){
$(this).parent().css("background-color", "rgba(203, 231, 57, 0.37)");
}
})
});
Assume I have 4 “th” elements on the page and on click of the button I need to create another “th” element but with specific position. For example if it’s 1997 it’ll be created in between 1995 and 2000 elements, and so on.
<table>
<tr>
<th>1990</th>
<th>1995</th>
<th>2000</th>
<th>2005</th>
</tr>
......
This is the code I have, but it creates new “th” at the very end.
var tblHeadObj = document.getElementById('<%=Me.GridView1.ClientID %>'); //table head
var newTH = tblHeadObj.rows[0].appendChild(document.createElement("th"))
LIVE DEMO
var doc = document,
ROW = doc.querySelectorAll("#myTable tr")[0],
BUTTON = doc.querySelector("#submit"),
INPUT = doc.querySelector("#setYear");
function isNumber(n) { // http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
return !isNaN(parseFloat(n)) && isFinite(n);
}
function createYear(){
var VAL = parseInt(INPUT.value, 10); // GET INPUT VALUE
var TH = ROW.querySelectorAll("th");
if(isNumber(VAL)){ // MAKE SURE IT?S A NUMBER
for(var i=0; i<TH.length; i++){ // LOOP TH ELEMENTS
var y = parseInt( TH[i].innerHTML, 10 ); // GET YEAR
if(y>VAL){ // ONLY IF y>VAL
var newTH = doc.createElement("th"); // CREATE NEW TH
newTH.innerHTML = VAL; // INSERT VALUE INTO TH
ROW.insertBefore( newTH, TH[i]); // https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore
break;
}
}
}else{
alert("PLEASE ENTER A YEAR");
}
}
BUTTON.addEventListener('click', createYear); // BUTTON CLICK
To insert html after the nth element using jquery:
$("th:eq(1)").after("<th>1997</th>");
...where 1 is your nth element.
check this out. you could use insertBefore()
https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore