Date script for Dropdown using Javascript/JQuery - javascript

I need to populate dropdown/ select list with calender dates in DD-MM-YYYY format, I have to do this in JavaScript and script should automatically fill Dropdown with dates for next 3 months.
I tried to look for such script but could not find. I would appreciate any help. i am open to use any jQuery if it works.
I have to fill dropdown with date in the format mentioned i cant use popup Calenders etc..
Example:
<select class="ddDates" id="Dates" name="Dates">
<option value="10-01-2012" selected>10-01-2012</option>
<option value="11-01-2012">11-01-2012</option>
<option value="12-01-2012">12-01-2012</option>
<option value="13-01-2012">13-01-2012</option>
</select>
I have searched google and i cant even find the logic how i can read system calender and populate the dropdown/ select list

This code generates the markup in question using JavaScript (and jQuery)
function pad(n){return n<10 ? '0'+n : n}
var date = new Date();
var selectElement = $('<select>'), optionElement;
for (var count =0; count < 90; count++){
date.setDate(date.getDate() + 1);
formattedDate = pad(date.getUTCDate()) + '-' + pad(date.getUTCMonth()+1) + '-' + date.getUTCFullYear();
optionElement = $('<option>')
optionElement.attr('value',formattedDate);
optionElement.text(formattedDate);
selectElement.append(optionElement);
}
You can change the value of count according to your logic.

jQuery UI's Datepicker:
http://jqueryui.com/demos/datepicker/

Related

Joined / Connected Dynamic Dropdowns

Greetings Stackoverflow Veterans,
I've been struggling for a little while with a small Input Safety Feature. Essentially, for my website users will get to pick a time they wish to start and end their morning shift.
I have two Select inputs which are populated by a date within a loop. Basically, what I've been trying (In vain) to achieve is that when someone picks a start date from the "Start Time" Dropdown, the "End Time" dropdown then has all values less than the "Start Time", disabled.
I've provided an image below to help explain a little better, and the current code I have as well in relation to how my select is working.
As for any progress on Javascript, there basically is none. Everything I have tried in no way works, and I'm starting to struggle to think of new ideas. I've spent plenty of time trying to find solutions here on StackOverflow but I might be searching with the wrong Keywords.
The start time has been selected on the Left Dropdown, at 07:00, but on the Right Dropdown, anything before 07:00 should now be removed / disabled.
<select id="mondayWorking_MorningStart" class="workInput" >
<?php
$tStart = strtotime($start);
$tEnd = strtotime($end);
$tNow = $tStart;
while($tNow <= $tEnd)
{
echo "<option id='monday_MorningStart' name='mondayMorningStart'>" . date("H:i",$tNow) . "</option>";
$tNow = strtotime('+30 minutes',$tNow);
}
?>
</select>
Thank you for your help,
If you need anything else to offer your help, please let me know!
To populate the second dropdown based on first drop down value, first you have to bind onChange event to first dropdown. It means that when you change the first dropdown and select another option, JavaScript(In our case jquery) will fire an event and run a code.
In that function(code) we get the value of the first dropdown, then clear the options of the second dropdown and refill the content of the second dropdown based on the first dropdown value.
I assumed that the second dropdown max value can be 24:00 and the min value should be equal to first dropdown value + 30 minutes...
I've just added a few options to first select for test. you are loading it with your php code and it makes no difference...
So the code will be like this:
$('#selStart').change(function(){
var arrTimeStart = $(this).val().split(":");
var timeStart = parseInt(arrTimeStart[0] * 60) + parseInt(arrTimeStart[1]);
timeStart = timeStart + 30;
var timeEnd = (24 * 60);
$('#selEnd').find('option').remove();
for (iCnt = timeStart; iCnt <= timeEnd; iCnt = iCnt + 30){
vHour = parseInt(iCnt / 60);
vMin = iCnt % 60;
if(vMin == 0)
vMin = '00';
tmpTime = vHour + ':' + vMin;
$('#selEnd').append('<option value='+tmpTime+'>'+tmpTime+'</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Start:
<select id="selStart">
<option value="00:00">00:00</option>
<option value="00:30">00:30</option>
<option value="01:00">01:00</option>
<option value="01:30">01:30</option>
<option value="02:00">02:00</option>
<option value="02:30">02:30</option>
<option value="03:00">03:00</option>
<option value="03:30">03:30</option>
<option value="04:00">04:00</option>
<option value="04:30">04:30</option>
</select>
<br>
End:
<select id="selEnd"></select>

setting html <select> option to be the default value based on current time

I have made a basic punchclock webpage & MySQL database,
only problem is when people accidently clock in instead of out at end of day or vice versa it leaves alot of gaps.
I need some sort of code that defaults "startfinish" value to "Start" before 10:30 and "End" after 14:30 but still allows the user to change the option if they needed to
note really sure where to start and if i should use javascript or php (php is in a seperate file as the "form action")
heres my current html code that needs the option changed:
<select name="startfinish" id="startend" required>
<option selected="selected" disabled selection>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
any help would be greatly appreciated
thanks,
Danial
If you aren't opposed to PHP you could check the current time and compare it against the times you've specified. This will have to go in the file you're working from though, not your action file.
<?php
// Set the default timezone so you don't run into timezone issues
// You can set this to whatever suits your application best
// Full list of supported timezones here: http://php.net/manual/en/timezones.php
date_default_timezone_set('America/Vancouver');
// Compare the current time to the start and end times
// This reads: if current time is before start time, option is selected, otherwise it's not
$start = (strtotime('now') < strtotime('10:30 AM today') ? 'selected="selected"' : '');
// This reads: if current time is after end time, option is selected, otherwise it's not
$end = (strtotime('now') > strtotime(' 2:30 PM today') ? 'selected="selected"' : '');
?>
To use this in your select control, you'd echo the variables (shown in shorthand for brevity) in the options. If the date calculations are correct, that option will be selected, otherwise it will remain unchanged. I removed the selection from the placeholder because this setup will ensure Start or End are always selected.
<select name="startfinish" id="startend" required>
<option disabled selection>Please select</option>
<option <?=$start?> value="Start">Start</option>
<option <?=$end?> value="End">End</option>
</select>
The benefit of using PHP in this case is that it runs server-side instead of client-side, so you don't have to worry about the user disabling Javascript and ruining your form design. Though, if you're already depending on jQuery in your application that's probably a non-issue.
You can use the Date object and a bit of jQuery to get the result you're after: http://jsfiddle.net/8cuL0k3h/
$(function() {
// Grab the date object and get hours/minutes
var current = new Date();
var hours = current.getHours();
var minutes = current.getMinutes();
// Check if time is before 10:30am
if( hours <= 10 && minutes < 30 ) {
$('#startend').val('Start');
}
// Check if time is after 2:30pm
else if( hours >= 14 && minutes > 30 ) {
$('#startend').val('End');
}
});
I'm assuming the site is statically generated, in which case PHP wont get a bite of this particular apple. Here's a JS only approach.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
initSelectElement();
}
function makeItemSelected(listElem, index)
{
var i, n = listElem.options.length;
for (i=0; i<n; i++)
{
if (index == i)
listElem.options[i].setAttribute('selected','');
else
listElem.options[i].removeAttribute('selected');
}
}
function initSelectElement()
{
var curTime = new Date();
var curHour = curTime.getHours();
var curMin = curTime.getMinutes();
if ((curMin <= 30) && (curHour <= 10))
{
makeItemSelected(byId('startend'), 1);
}
else if ((curMin >= 30) && (curHour >= 2))
{
makeItemSelected(byId('startend'), 2);
}
}
</script>
<style>
</style>
</head>
<body>
<select name="startfinish" id="startend" required>
<option selected disabled>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
</select>
</body>
</html>

Simple Hotel Booking Form Total Calculation

I wonder if anyone can help me... Unfortunately I do not have any Javascript knowledge and finding it a bit difficult to understand.
I am working on a Hotel Booking form and this is what I need to do. There is an option to choose the hotel as well as the options for how many nights are required.
There is also a Totals field. This is where I am stuck. Can someone help me with a script or what to do get the Total field to show the total of the formula of nights times choice of hotel?
This would also need to be a value that would be posted with the other values to the php form which in turn sends me the email with the values.
Here is the link to the form I made: https://www.alpinemalta.net/libyabuild2013/bookNow.html
Thank you to anyone that can help me and please excuse my lack of knowledge in this area.
Regards
Chris Brown (Malta)
looking at your form,
1) i think the drop down list for total of nights is redundant (the total of nights is clear from arrival and departure dates)
2) the dates (for having it simpler using it in JavaScript) use numeric values instead of: '11/05/2013(A)' or such.
<select name="ArrivalDate" size="1" id="ArrivalDate">
<option>Please select</option>
<option value="1368399600">13-05-2013</option>
<option value="1368486000">14-05-2013</option>
...
</select>
3) i didn't notice anywhere the price per night? Maybe the list of hotels could also contain some ID (such as h1a,h1b, h2a, h3a, h3b, h3c, ...) instead of the textual option description (of hotel and room)
<select name="hotel_choice" id="hotel5">
<option value="nothing" selected="selected">None Selected</option>
<option value='nothing'>.</option>
<option value="h1a">Corinthia Single Room</option>
<option value="h1b">Corinthia Double Room</option>
<option value='nothing'>.</option>
...
</select>
if you do that then the JavaScript may not be that complicated (asuming you do those changes and don't mind having the price for each hotel visible in the page source):
<script type='text/javascript'>
var prices={nothing:0,h1a:357,h1b:280.50,h2a:380}; //here are your hotel prices
function calculate() {
var days = Math.round( (
document.getElementById('datedepart').value -
document.getElementById('ArrivalDate').value
) / 86400 ); //timestamp is in seconds
document.getElementById('total_cost').value =
days *
prices[ document.getElementById('hotel5').value ];
}
</script>
please note that there aren't any niceties in the code and it's based on the assumption, that the dates are changed to their representative integer values (such as are returned by php function time() ) also it is possible that i made an error in the ID names of your elements
Then what remains is to hook up the "calculate();" javascript function to onchange event of all the controls and you are done.
<select name="hotel_choice" id="hotel5" onchange='calculate();'>
...
</select>
and
<select name="ArrivalDate" size="1" id="ArrivalDate" onchange='calculate();'>
...
</select>
and the same in the departure date selector.
EDIT:
You could use dates in your date selectors, but you would have to parste that string into a number client side using something like:
var dt=Date.parse(document.getElementById('ArrivalDate').value);
But make sure to check supported date formats for this function and also note it returns the number of milliseconds since 1970 so you will have to be dividing by 86400000 instead of 86400
EDIT - check for dates are filled in
function calculate() {
var dd=document.getElementById('datedepart');
var da=document.getElementById('ArrivalDate');
var total=document.getElementById('total_cost');
var hotel=document.getElementById('hotel5');
//no hotel room selected or not depart date set or not arrival date set
//or departing before arrival (nonsense) - set total to ZERO and exit the function
if ( !(dd.value*1) || !(da.value*1) || da.value>dd.value ) {
total.value='0';//you can set it to 'not allowed' also if you wish (instead of '0')
return;
}
var days = Math.round( (
dd.value -
da.value
) / 86400 ); //timestamp is in seconds
var cost = days * prices[ hotel.value ];
if (isNaN(cost))
cost = 0; //or set to "invalid input" - but this line should not be needed at this point
total.value = cost;
}

javascript function to show current time as pre-selected value of html select tag

I want to have two select tags in html, one for hour and one for minutes. I want the default value of hour to be set on current hour and the value of minute to be set on current minute. I think with default time to be set for example on 3, i should have some thing like this:
<select name="hour">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
...
<option value="23">23</option>
</select>
now my question is how can i use javascript to show the current hour and minutes by default?
There are JavaScript Date methods called .getHours() and .getMinutes(). So given:
<select id="hour" name="hour">...</select>
<select id="minute" name="minute">...</select>
You can do something like the following in a script block that appears after the selects (or is called onload or on DOM ready):
var currentDateTime = new Date();
document.getElementById("hour").value = currentDateTime.getHours();
document.getElementById("minute").value = currentDateTime.getMinutes();
Depending on how you're creating the option elements, one approach is to use:
var now = new Date(),
// we're adding one because JavaScript returns zero-based hours, 0-23
hour = now.getUTCHours() + 1,
sel = document.getElementById('hours'),
opt;
for (var i=0; i<24; i++){
opt = document.createElement('option');
opt.value = i;
opt.textContent = i;
sel.appendChild(opt);
if (i == hour) {
opt.selected = true;
}
}
JS Fiddle demo.
This uses the JavaScript Date() methods, getUTCHours()
If your option elements are already set in the HTML, and you're simply changing which is selected by default:
var now = new Date(),
hour = now.getUTCHours() + 1,
sel = document.getElementById('hours'),
curHour = sel.getElementsByTagName('option')[hour];
curHour.selected = true;
JS Fiddle demo.
References:
Date().

Populate a input with a date based on selected option (date today + days)

How to do this using jQuery
i have a select like
<select id="Plan_Id" name="Plan_Id">
<option value="30">Month</option>
<option value="365">Annual</option>
</select>
then i have a input
<input name="date" id="date_picker" type="text" class="text date_picker" />
so based on the option i select i want to get the date today + value and show on the input was
m-d-Y.
so if today is january 07 and i select 30 -> month
my input will be populated with 02-06-2012
Rather than general googling, you want to look specifically at a JavaScript reference about the Date object and at the jQuery UI datepicker reference. Between the two you'll have all the information you'll need to work this out. But since I already happen to know the answer (or an answer)...
Given a JavaScript date object:
var today = new Date(); // current date returned by constructor with no params
You can add n days to it by setting the day-of-the-month to the current value plus n - the month and/or year will be automatically adjusted as appropriate. So:
today.setDate(today.getDate() + 30);
today.setDate(today.getDate() + 365);
Put together with the jQuery datepicker "setDate" method:
var theDate = new Date();
theDate.setDate(theDate.getDate() + 365);
$("#date_picker").datepicker("setDate", theDate);
Demo: http://jsfiddle.net/WUdWs/1/
Here is my way http://jsfiddle.net/gurkavcu/bRXmK/
$(function() {
$("#date_picker").datepicker({
onSelect: function(dateText, inst) {
// Create selectedDay
var selectedDay = new Date(inst.currentYear,inst.currentMonth,inst.currentDay);
// Add day amount according to select box
selectedDay.setDate(selectedDay.getDate()+parseInt($("#Plan_Id").val(),10));
// Show new day with your own style
$(this).val((selectedDay.getMonth()+1)+"-"+
selectedDay.getDate()+"-"+
selectedDay.getFullYear());
}
});
});

Categories