Date as class in datepicker - javascript

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?

Related

Remove a whole table if all rows are removed using jQUery

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();
}
});

Creating Dependent Chechboxradio Buttons - jQuery Mobile

I am trying to create several checkboxradio buttons groups in jQuery mobile that depend on a limit checkboxradio button group value. For example if a limit of 6 is selected I want to only allow the user to be able to select up to a total of 6 children based on all of the other checkboxradio button group selected values and disable everything else. When the limit changes I want to update the UI accordingly.
I have the following code in my change event handler whenever any of the checkboxradio buttons are clicks:
function updateUI(element) {
var limit = parseInt($('input[name="Limit_Total"]:checked').val(), 10);
// Children
var childCount = parseInt($('input[name="Child_Total"]:checked').val(), 10);
var secondChildCount = parseInt($('input[name="Second_Child_Total"]:checked').val(), 10);
var thirdChildCount = parseInt($('input[name="Third_Child_Total"]:checked').val(), 10);
var fourthChildCount = parseInt($('input[name="Fourth_Child_Total"]:checked').val(), 10);
var fifthChildCount = parseInt($('input[name="Fifth_Child_Total"]:checked').val(), 10);
// Totals
var totalChildern = childCount + secondChildCount + thirdChildCount + fourthChildCount + fifthChildCount;
// Enable the correct combination of children
$('input[name*="Child_Total"]').not(element).checkboxradio('disable').checkboxradio('refresh');
for (var i = 0; i <= 6; i++) {
if (i <= (limit - totalChildren)) {
$('input[id$="Child_Total_' + i + '"]').not(element).checkboxradio('enable').checkboxradio('refresh');
} else {
$('input[id$="Child_Total_' + i + '"]').not(element).attr('checked', false).checkboxradio('refresh');
}
}
}
I basically want to simulate the behavior illustrated in the image below:
The problem is it doesn't quite give me the behavior I want. It deselects all but the button I select within the group. I am trying to figure out the most efficient way to do this but I am having a hard time. Any suggestions or help would be greatly appreciated!
I have setup the following jsfiddle to demonstrate the UI: http://jsfiddle.net/X8swt/29/
I managed to solve my problem with the following function:
$('div fieldset').each(function() {
// Disable all none checked inputs
$(this).find('input:not(:checked)').checkboxradio().checkboxradio("disable").checkboxradio("refresh");
// Grab the selected input
var selectedElement = $(this).find('input:checked');
// Calculate the remaining children that can be selected
var remaining = (limit - totalChildern);
// Enable all inputs less than the selected input
$.each($(selectedElement).parent().prevAll().find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
// Enable up to the remaining boxes past the selected input
$.each($(selectedElement).parent().nextAll().slice(0,remaining).find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
});
Please feel free to comment or critique my solution.

JQuery clone click add more button if i select the previous row date not updating and when click delete the top total result value was not reducing

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);

Jquery each only adds the first elements

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);

Dynamically changing costs in custom pc builder with checked inputs

First, please take a look at my fiddle.
I'm trying to figure out a clean way of making the price next to each item change when any item is selected (in that group, you can image that there will be graphics cards etc in a different section which also will need the same functionality).
If its positive I need the class to be .positive and vice versa, and if the item is selected (+0) then the price difference wont be displayed.
This will also be used on checkbox's.
Non-working example.
You'll want to compare each selected item with items having the same name. In the .each() loop in CalculatePrice(), pass the checked item to this function:
function CalculateDiffs(item) {
var selectedPrice = +item.data("price");
item.siblings(".item_price").text("");
$(".calculation-item[name='"+item.attr("name")+"']").not(item).each(function(){
var price = +$(this).data("price");
var diff = (price-selectedPrice).toFixed(2);
if (diff >= 0) {
diff = "+"+diff;
}
$(this).siblings(".item_price").toggleClass("negative", diff < 0).text(diff);
});
}
As for checkboxes, the above function will take care of hiding the price when it is checked. To display the prices for unchecked checkboxes:
$(".calculation-item:checkbox:not(:checked)").each(function(){
$(this).siblings(".item_price").text("+"+$(this).data("price"));
});
Or, if you want to display the price of a checked checkbox as negative, use this instead:
$(".calculation-item:checkbox").each(function(){
var diff = (this.checked ? "-" : "+") + $(this).data("price");
$(this).siblings(".item_price").toggleClass("negative",this.checked).text(diff);
});
http://jsfiddle.net/gilly3/HpEJf/8/
Actually it's pretty straight forward, all you'll need to do is calculate the difference between the selected price and the price of all the options in the list. Eg, something like this:
$(".calculation-item").each(function(index) {
var my_cost = base_price + $(this).data("price");
var difference = Math.round(my_cost - base_cost);
});
I've created a working jsFiddle for you here: http://jsfiddle.net/HpEJf/6/. You'll need to implement decimal rounding etc but this should put you on the right track :)
If my understanding is correct, you want to display the cost difference from the previously selected radio button and the currently selected radio button.
To do that you need to keep track of the previously selected button. The only way I know of to do that is to set a variable outside the clickhandler scope to keep track of it and update the element in the clickhandler.
The rest is fairly straightforward. I updated your jsFiddle with an example of how to do it. The relevant code is below:
Adding at top of script:
//global for last checked/selected radio
var lastSelection = $(".calculation-item:checked");
//clear existing price diffs set by markup
$('span.processor_price').text('');
Added another function:
function priceDifference(oldPrice, newPrice) {
var difference = {
'cssClass': '',
'inCost': '0'
};
var fixedDiff = '';
var diff = newPrice - oldPrice;
diff = Math.ceil(Math.abs(diff * 100)) / 100;
fixedDiff = diff.toString();
if (newPrice < oldPrice) {
difference.cssClass = 'negative';
difference.inCost = '-' + fixedDiff;
} else if (newPrice > oldPrice) {
difference.cssClass = 'positive';
difference.inCost = '+' + fixedDiff;
}
/* else {
* must be the same, no reason for this block
* as the default empty string will suffice
* as will the cost difference of 0
}*/
return difference;
}
And changed your click handler to:
$(".calculation-item").click(function() {
var difference = {};
if (lastSelection) {
//get difference
difference = priceDifference($(lastSelection).data("price"), $(this).data("price"));
//change class
$(this).siblings('span.processor_price').addClass(difference.cssClass).text(difference.inCost);
$(lastSelection).siblings('span.processor_price').removeClass('positive').removeClass('negative').text('');
if (lastSelection !== this) {
lastSelection = this;
}
} else {
lastSelection = this;
}
CalculatePrice();
});​

Categories