Passing data to another function without repeating code - javascript

I have form with input fields for some service, now I have trouble how to pass data from to function.
This form accept number and this number is multiplied to get total price, but some inputs can be 0.
I declare in globals to get value from the inputs
var cleaning_size;
var bathroom_number;
$( ".needs-validation" ).on( "change", "input", function() {
cleaning_size = $("#cleaning-size").val();
bathroom_number = $("#bathroom-numbers").val();
})
And in the form i have datepicker where you chose date, but if selected sunday the price calculation is different
$("#datepicker").datepicker({
changeMonth: true,
onSelect: function (selectedDate) {
var date = $(this).datepicker('getDate');
var day = date.getUTCDay();
if (day == '6') {
price_cleaning_size = 1.5;
price_bathroom_number = 26;
} else {
price_cleaning_size = 1.2;
price_bathroom_number = 24;
}
}
});
And then i calculate total in different function:
function calculate_total_value(){
var cleaning_size_price = cleaning_size * price_cleaning_size;
var bathromm_number_price = bathroom_number * price_bathroom_number;
var total_price = cleaning_size_price + bathromm_number_price;
$('#total-price strong').text(total_price).val();
}
Now i have issue how to get data from the datepicker if selected day is 6 to get 1.5 or 1.2 to calculate total price.
I can't find any similar example how to do this.
Also i will have timepicker what will be inside function and i will need to get value from there.
So how to pass value the right way please?

Try modifying your function (calculate_total_value()), so it accepts two parameters - these two parameters are the values that you modify based on the selected day.
(And also check for typos like bathromm_number_price - they can take a lot of time to "find" later on.)
jQuery(document).ready(function($) {
var cleaning_size;
var bathroom_number;
$(".needs-validation").on("change", "input", function() {
cleaning_size = $("#cleaning-size").val();
bathroom_number = $("#bathroom-numbers").val();
})
$("#datepicker").datepicker({
changeMonth: true,
onSelect: function(selectedDate) {
var date = $(this).datepicker('getDate');
var day = date.getUTCDay();
if (day == '6') {
price_cleaning_size = 1.5;
price_bathroom_number = 26;
} else {
price_cleaning_size = 1.2;
price_bathroom_number = 24;
}
// call the function here, passing the values as parameters
calculate_total_value(price_cleaning_size, price_bathroom_number)
}
});
// alter your function, so it accepts two parameters (price_cleaning_size, price_bathroom_number)
function calculate_total_value(price_cleaning_size, price_bathroom_number) {
var cleaning_size_price = cleaning_size * price_cleaning_size;
var bathromm_number_price = bathroom_number * price_bathroom_number;
var total_price = cleaning_size_price + bathromm_number_price;
$('#total-price strong').text(total_price).val();
}
})
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="needs-validation">
<label for="cleaning-size">Cleaning size:
<input id="cleaning-size" type="number"></label>
<label for="bathroom-numbers">Bathroom number:
<input id="bathroom-numbers" type="number"></label>
</div>
<h2 id="total-price"><strong>0</strong></h2>
<p>Date: <input type="text" id="datepicker"></p>

price_cleaning_size , price_bathroom_number aren't declared anywhere.
It is recommended to declare the variable.(when you use use strict, it's must). Declare it globally.
No where you are calling the function calculate_total_value().
It's good to call it right at bottom of onSelect call back of datepicker.
$("#datepicker").datepicker({
changeMonth: true,
onSelect: function (selectedDate) {
var date = $(this).datepicker('getDate');
var day = date.getUTCDay();
if (day == '6') {
price_cleaning_size = 1.5;
price_bathroom_number = 26;
} else {
price_cleaning_size = 1.2;
price_bathroom_number = 24;
}
calculate_total_value();
}});
When your variable scope is global, There is no point of passing as parameter to the function. Hope there is reason to declare it globally.
Hope this helps you...

Related

Javascript Add two Integer Variables?

So I am trying to create something where when a user clicks a div element, it adds a number to a total, sort of like a checkout system.
I have written the following javascript
JS
var optionOne = 5;
var optionTwo = 10;
var basePrice = 0;
function doMath() {
$("#option1checkout").click(function() {
// Add optionOne to basePrice
});
$("#option1cancel").click(function() {
// Don't do anything to basePrice
});
$("#option2checkout").click(function() {
// Add optionTwo to basePrice
});
$("#option2cancel").click(function() {
// Don't do anything to basePrice
});
};
I want it to add option 1 and 2 to basePrice whenever they click the option1checkout or option2checkout div element and do nothing when they click the cancel div elements.
I just feel like if I just do "basePrice + optionOne;" in the click functions it would be manual and not actually adding the integer values.
Any other way to do this?
What wrong with this approach:
var mousePrice = 5;
var coverPrice = 10;
var mouseSelected=0;
var coverSelected=0;
var basePrice = 500;
function doMath() {
$("#mouse").click(function() {
basePrice+=mousePrice;
});
$("#omouseCancel").click(function() {
if(mouseSelected>0){
basePrice-=(mousePrice*mouseSelected);
}
});
$("#cover").click(function() {
basePrice+=coverPrice;
});
$("#coverCancel").click(function() {
if(coverSelected>0){
basePrice-=(coverPrice*coverSelected);
}
});
};

show future date and time

I want to show the future date and time in the date and time field components.
Below is the sample code:
require([
"dojo/_base/lang", "dijit/registry", "dojo/ready", "dijit/form/TimeTextBox", "dojo/parser"
], function(lang, registry, ready) {
ready(function() {
var time = registry.byId("time");
time.set("constraints", lang.mixin(time.get("constraints"), {
min: 'T08:00:00'
}));
});
});
In the above code min constraint is used to disable time before 8:00AM , but i want to disable the past time and if user selects future date the time should not disable.Please suggest. Thanks.
--EDITED--
jsp page:
Date<input type="hidden" name="userDate" value="${myDTO.USER_DATE}"/> <input name="USER_DATE" id="oracle" value="${myDTO.USER_DATE}" required="true"/>
Time: <input type="hidden" name="userTime" value="${myDTO.USER_TIME}"/> <input id="time" data-dojo-type="dijit/form/TimeTextBox" onChange="require(['dojo/dom'], function(dom){dom.byId('val').value=dom.byId('time1').value.toString().replace(/.*1970\s(\S+).*/,'T$1')})"
data-dojo-props="constraints: { timePattern: 'HH:mm:ss', clickableIncrement: 'T00:15:00', visibleIncrement: 'T00:15:00', visibleRange: 'T01:00:00' }" />
js:
require(["dijit/form/TimeTextBox", "dojo/domReady!"], function(TimeTextBox){
function showTimeValue(){
try{
dom.byId('val').value = document.getElementsByName('time')[0].value;
}catch(err){}
}
new TimeTextBox({
name: "time",
value: document.getElementsByName('userTime')[0].value,
onChange: function(v){ setTimeout(showTimeValue, 0);},
constraints: {
timePattern: 'HH:mm:ss',
clickableIncrement: 'T00:15:00',
visibleIncrement: 'T00:15:00',
visibleRange: 'T01:00:00'
}
}, "time").startup();
showTimeValue();
});
// for Dynamic date value
//code for Date field
// ....
new OracleDateTextBox({
value: document.getElementsByName('userDate')[0].value,
name: "oracle",
required: true,
onChange: function(v){ ...}
You can achieve this by accessing your time element inside the onchange callback of your DateTextBox. You will need to inject all the time widget dependencies into your second require statement. When the date changes, check if it is today and otherwise allow the user to select all time slots.
Here is an updated fiddle: http://jsfiddle.net/8o23tbLu/1/
onChange: function(v){
var useMin, now, time, pad;
pad = function(n) {
n = n + '';
return n.length >= 2 ? n : new Array(2 - n.length + 1).join('0') + n;
}
useMin = 'T00:00:00';
now = new Date();
if ((now.getDate() === v.getDate()) &&
(now.getYear() === v.getYear()) &&
(now.getMonth() === v.getMonth())
){
var hour = pad(now.getHours());
var minute = pad(now.getMinutes());
useMin = 'T' + hour + ':' + minute + ':00';
}
time = registry.byId("time");
time.set("constraints", lang.mixin(time.get("constraints"), {
min: useMin
}));
setTimeout(showServerValue, 0);
}

How to Apply multiple styles on days

I have to mark three kind of days with different styles: Out_of_window, Free or Unavailable. The unavailable has to be disabled.
I made a function based on this question. And I had to remove the default datepicker class (ui-state-default) otherwise I couldn't change the bg-image.
Everything work as desired, until I change month. When I get back to original month, the day gets back its orignal class (ui-state-default) and I have no more my customized styles according the kind of day.
So, I have the following codes:
var pick_up_out_of_window_dayDates = new Array("2012-12-11","2012-12-12");
var pick_up_free_dayDates = new Array("2012-12-21","2012-12-22");
(as global ones)
function applyDayStyles(date){
var enabled = true;
var cssClass = "";
console.log(date);
var day = date.getDate();
var month = date.getMonth() + 1; //0 - 11
var year = date.getFullYear();
var compare = year + "-" + month + "-" + day;
var pick_up_out_of_window_day = pick_up_out_of_window_dayDates.indexOf(compare) + " " + compare
var pick_up_free_day = pick_up_free_dayDates.indexOf(compare) + " " + compare
if (pick_up_out_of_window_dayDates.indexOf(compare) >= 0){
cssClass = "pick_up_out_of_window_dayCalendar";
console.log(1);
return new Array(enabled, cssClass, pick_up_out_of_window_day);
}
else
if (pick_up_free_dayDates.indexOf(compare) >= 0){
cssClass = "pick_up_free_dayCalendar";
console.log(2);
return new Array(enabled, cssClass, pick_up_free_day);
}
else
return new Array(false, cssClass, date);
}
$(document).ready(function() {
$(".datepicker").datepicker({
minDate: 0,
beforeShowDay: applyDayStyles
})
//{edited}
// this is un necesssary !
// $('.pick_up_free_dayCalendar').children().removeClass('ui-state-default').addClass('pick_up_free_dayCalendarIN'); // I Had to add this line to remove the defaukt bg style.
})
Any thoughts?
Just have to override the default class :
.datepicker .pick_up_out_of_window_dayCalendar .ui-state-default {background: red;}
.datepicker .pick_up_free_dayCalendar .ui-state-default {background: blue;}
Thanx to #adeneo (see questions' coments)
http://jsfiddle.net/Cwg3P/2/

Highlight <TR> entire week datepicker

I have a datepicker that is fully functional and is working whereby you can select an entire commencing working week (Mon-Fri). What I am now trying to do is extend it a little further so that when I click on a specific week. It will highlight that entire . I have it paritally working which looks like the following: Calandar preivew. It can be seen that the problem I am having is that the table row to me seems to be doing a odd, even, odd even. As for the first week I highlight the row is highlighted in red and the cells are hihglighted in yellow. Then the week afer that it work fines and then if I was to select the week after that the same would be repeated. I tried checking the jquery-ui-1.8.4.custom.css and the jquery-ui.css, and had no luck. What seems to confuse me is why are the cells being highlighted in yellow? The code follows for my datepicker.
Javascript:
$(function()
{
var startDate;
var endDate;
var selectCurrentWeek = function()
{
window.setTimeout(function () { $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')}, 1);
}
function check(d) {
if(d.length() == 2) {
dd = d;
return dd;
} else {
dd = "0" + myDateParts[0];
return dd;
}
}
var selectedWeek;//remember which week the user selected here
$('.week-picker').datepicker( {
beforeShowDay: $.datepicker.noWeekends,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 1);
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = 'yy-mm-dd'
var newDate = $('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
var oldDate = document.getElementById('startDate');
var date_textnode = oldDate.firstChild;
var date_text = date_textnode.data;
myDateParts = date_text.split("-");
var dd = myDateParts[2];
var mm = myDateParts[1];
var yy = myDateParts[0];
selectCurrentWeek();
window.location.href = "/timesheet?week_commencing=" + yy + "-" + mm + "-" + dd;
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$( ".week-picker" ).datepicker().click(function(event) {
// highlight the TR
$(".ui-datepicker-current-day").parent().addClass('highlight');
// highlight the TD > A
$(".ui-datepicker-calendarr-day").siblings().find('a').addClass('white');
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
HTML
<div class="datepicker borderbox">
<b><center>Hours for Week commencing: <span id="startDate"></span></center></b>
<div class="week-picker"></div>
</div>
CSS
.highlight {
border: 1px solid red;
}
.white {
background: white !important;
}
I have tried looking at the following stackoverflow question Related stackoverflow. Had no luck with this, as the link was broken and also tried viewing the it in JSfiddle. Further to this the way I have set my datepicker is different.
I am intially trying to get my calendar to work like this But for some reason when I try do this I get the following. Is this something to do with the css
Update2
Calendar & Firebug output
Is this what you want?
http://jsfiddle.net/william/YQ2Zw/2/
There were a couple of things that went wrong:
The ui-datepicker-current-day class was applied to a <td> element, so it only needs to travel one level up to find the <tr>, so I took away one call to parent():
$(".ui-datepicker-current-day").parent().addClass('highlight');
You set multiple days with the ui-datepicker-current-day class. That was why I needed to use the :eq(0) selector to only select the first element:
$(".ui-datepicker-current-day:eq(0)").siblings().find('a').addClass('white');
Also, you were calling the wrong class for the statement above.

Events in jQuery UI Datepicker with json data source

I want to display events in the jQuery UI Datepicker. I want the days that have events to be styled differently from days that don't have events, and I want to display a custom tooltip with the event details when hovering dates with events.
The solution to the question "jQuery UI Datepicker with jQuery tipsy" gets very close, but doesn't work with the Datepicker configuration I use. I use the "showOtherMonths" option, and it throws the date link calculation off.
The event data is available at http://mydomain.com/events.json
Mockup of what I want:
This is the code I use for creating the Datepicker:
$('#dateDiv').datepicker({
altField: '#dateInput',
altFormat: 'yy-mm-dd',
dateFormat: 'yy-mm-dd',
firstDay: '1',
showOtherMonths: 'true',
});
I'm not concerned about the CSS part of the solution at this time, just the javascript part. How do I make my custom tooltip appear when hovering the dates with events attached to them? And how do I attach the events (calendar events, not javascript/DOM events ;) )?
This is not a very elegant solution, but it does seem to work. Can someone please come up with something better?
EDIT: Here's a jsFiddle with the code running: http://jsfiddle.net/Tobbe/JrkSN/3/
EDIT2: It works until I click on a date, then all the events disappears because the beforeShowDay callback isn't called in that case. How do I work around that?
getEvents();
$(function() {
$('#dateDiv').datepicker({
altField: '#dateInput',
altFormat: 'yy-mm-dd',
dateFormat: 'yy-mm-dd',
firstDay: '1',
showOtherMonths: 'true',
beforeShowDay: beforeShowDay,
onChangeMonthYear: getEvents
});
});
var enqueuedDates = [];
var tryCounter = 0;
var events = [];
function getEvents() {
events = [];
enqueuedDates = [];
$.getJSON('events.json', function(json) {
events = json;
});
}
function beforeShowDay(date) {
enqueuedDates.push(new Date(date));
if (enqueuedDates.length == 35) {
processEnqueuedDates();
}
return [true, '', ''];
}
function processEnqueuedDates() {
if (!events || events.length === 0) {
tryCounter++;
if (tryCounter < 100) {
setTimeout(processEnqueuedDates, 10);
} else {
tryCounter = 0;
}
return;
}
tryCounter = 0;
for (var i = 0; i < enqueuedDates.length; ++i) {
var event = getEvent(events, enqueuedDates[i]);
if (event) {
var theDateCells = $('#dateDiv .ui-datepicker-calendar td');
var hideTimeoutID;
theDateCells.eq(i).addClass('eventPlanned').
bind('mouseenter', function(eventText) {
return function() {
if (hideTimeoutID) {
clearTimeout(hideTimeoutID);
hideTimeoutID = null;
}
var popup = $('#eventPopup');
if (popup.size() == 0) {
popup = $('<div></div>').attr('id', 'eventPopup');
$('body').append(popup);
}
var pos = $(this).offset();
popup.html('<p>' + eventText + '</p>').
css('left', pos.left + 5 + 'px').
css('top', (pos.top - popup.height() - 2) + 'px').
bind('mouseenter', function() {
clearTimeout(hideTimeoutID);
hideTimeoutID = null;
}).
bind('mouseleave', function() {
$(this).hide();
}).
show();
}
}(event.text)).
bind('mouseleave', function(eventObject) {
hideTimeoutID = setTimeout(function() {
$('#eventPopup').hide();
}, 200);
});
}
}
}
function getEvent(events, date) {
return events.filter(function(event, index, arr) {
return date - $.datepicker.parseDate('yy-mm-dd', event.date) === 0;
})[0];
}

Categories

Resources