How to select date on click from Bootstrap Datepicker - javascript

I have Bootstrap Datepicker and I want to set default date when click on Set Date button.
HTML
<div class="input-append date datepicker no-padding" data-date-format="dd-mm-yyyy">
<input class="input-medium" id="date" size="16" type="text"><span class="add-on"><i class="icon-th"></i></span>
</div>
Set Date
jQuery
$(document).ready(function() {
$('.datepicker').datepicker();
$("#set_date").click(function(){
date ="07/01/2015";
$("#date").val(date);
});
});
I set date using jQuery but it do not show as selected date. My question is How to set date on click and show as selected date.
JS Fiddle

read this http://api.jqueryui.com/datepicker/#method-setDate
here after update your example
http://jsfiddle.net/tuG6C/614/
$(document).ready(function() {
$('.datepicker').datepicker();
$("#set_date").click(function(){
date ="07-01-2015";
//$("#date").val(date);
$( '.datepicker' ).datepicker( "setDate", date );
});
});

Update your javascript with
$(document).ready(function() {
$('.datepicker').datepicker();
$("#set_date").click(function(){
date ="07/01/2015";
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var today = curr_month + "/" + curr_day + "/" + curr_year;
$("#date").val(today);
});
});
check js fiddle
http://jsfiddle.net/swapnilmotewar/tuG6C/609/

Please replace:
$("#date").val(date);
With:
$(".datepicker").datepicker("update", date);

Related

Trying to only allow date picking to be between 45-90 days from today's date

This is the code I have so far but I am not sure how to alter this function to also check if the selection was made after 90 days. What I have so far is when you click the date picker, it will jump to 45 days from today and not allow user to choose anything from prior, but the problem is that it will allow past 90 days which is what i dont want.
https://jsfiddle.net/dwyvtajg/
<label id="asterisk">*</label> <label class="description" for="element_2">Event Date:</label><br /><label>Reservations must be made between <b>45-90 days in advance</b> of the event date</label> <br /><input onclick="one()" required="" type="date" oninput="this.className = ''" name="Event-Date" id="datepicker1" min="2019-10-02" />
<script>if ( $('#datepicker1')[0].type != 'date' ) $('#datepicker1').datepicker();</script>
<script>
function formatISOLocal(d) {
let z = n => ('0' + n).slice(-2);
return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}
function one() {
let inp = document.querySelector('#datepicker1');
let d = new Date(new Date().getTime()+(45*24*60*60*1000));
inp.min = formatISOLocal(d);
inp.defaultValue = inp.min;
d.setFullYear(d.getFullYear() , d.getMonth() + 6);
inp.max = formatISOLocal(d);
// Debug
console.log(inp.outerHTML);
}
</script>
thanks for the help everyone.... editing this line fixed it!!!
d.setFullYear(d.getFullYear() , d.getMonth() , d.getDate() +45);
Definitely take like an hour to review the docs. You're making things so much harder on yourself otherwise.
For instance, setting a min and max date - voila:
$(function() {
$( "#datepicker1" ).datepicker({
maxDate:'+90d',
minDate: '+45d',
onSelect: function(date) {}
});
});

Select a date 7 days after current date in javascript

I have input in html like this:
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
I would like to select a date that is more than 7 days from the current date, if I select a date before 7 days from current, it should prompt saying "Wrong date selected"
How do I do that in javascript?
I tried the following:
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
It gives the date correctly. How do I use this to compare if date is 7 after or not and prompt accordingly?
Thanks!
UPDATE:
<html>
<body>
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
</body>
</html>
<script>
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e)
{
var selectDate = e.target.value
var startDate = new Date(Date.parse(selectDate));
console.log(startDate);
var dateAfter7Days = new Date(new Date().getTime()+(7*24*60*60*1000))
console.log("7 days " + dateAfter7Days);
if (startDate => dateAfter7Days )
{
console.log("Allow");
}
else
{
console.log("Don't allow");
}
}
</script>
I am getting "Allow" for any date I select.
The point is comparing two date values. If current date - selected date > 7 then it should print prompt. The problem is how to get selected date.
You can get the selected date from the input tag by event value. On changed date, the value get logged.
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e) {
console.log(e.target.value);
}
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
var date = new Date();
var next_seven_date = d.getDate()+7;
var current_month = d.getMonth();
current_month++; // month start from 0 then we need to +1
var current_year = d.getFullYear();
var weekDate =(next_seven_date + "/" + current_month + "/" + current_year);
date.setDate(weekDate);
Since your problem is to compare dates not creating them I have updated my answer which might hlp you
var currentDate= new Date();
currentDate= new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate(),0,0,0)
var idealDifference= (7*24*60*60*1000);
//In your case this date might comes from some date selection user control. Be aware to make the time part of each date to same
var userSelectedDate = new Date(2021, 04, 04,currentDate.getHours(),0,0,0)
if((userSelectedDate.getTime()-currentDate.getTime())>=idealDifference)
{
console.log(userSelectedDate, ' is after 7 days from ',currentDate)
}
else
{
console.log(userSelectedDate, ' is before 7 days from ',currentDate)
}
Note: It is important to unset the time part of both the dates before comparing for this logic to work

jQuery finding descendant by ID not working

I'm trying to change the value of a jQuery datepicker input element in a form to the first date in the week of the user-selected date once the submit button is clicked but before the form is actually submitted.
I'm finding that the following Javascript works (using a class selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find('.week-picker').datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
startDate is a Date object.
But this code does not work (using an ID selector in .find()):
$("form").submit( function(event) {
$(this).closest('form').find("#week-picker").datepicker( "setDate", startDate );
var current_date = $(this).closest('form').find('.week-picker').datepicker( "getDate" );
return;
});
console.log($(this).closest('form').find(".week-picker").datepicker( "setDate", startDate ).val()); produces a proper date, like 06/27/2018.
console.log($(this).closest( 'form' ).find('#week-picker').val()); produces undefined.
Why is this happening? Isn't an ID a valid selector?
HTML:
<form action="/checkin" method="post">
<div class="form-group row mb-2">
<div class="col-md-6 offset-md-3">
<input class="week-picker form-control" type="text" id="week-picker" name="week_start" placeholder="Select week" style="opacity: 0;position: absolute;">
</div>
</div>
<div class="form-group row mt-4">
<div class="col">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</div>
</form>
The datepicker portion of my JS:
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$(this).closest( 'form' ).find('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$(this).closest( 'form' ).find('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$(document).on( 'mousemove','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').addClass('ui-state-hover'); });
$(document).on('mouseleave','.week-picker .ui-datepicker-calendar tr',function() {$(this).find('td a').removeClass('ui-state-hover'); });
#week-picker is a valid selector, as long as your input has that ID assigned. What is happening in your case is that there is JS turning your input into a datepicker, and it changes the ID of the element when it loads. As you posted from your element inspector, your input no longer has the week-picker ID, it is now dp1529862475978.
This is not uncommon, and the behavior you're getting is the expected one. If you need to make sure that you're targeting this datepicker instead of another one with the same class, you can use the name attribute:
$("input[name='week_starting']")
You should never have 2 inputs with the same name on the same page, so it's as unique as an ID. The ID you're seeing in the element inspector is probably randomly generated, so you don't want to use that.

How to autoinsert date in second field after there were already inserted some date into the 1st field?

Lets say i have two fields:
Start Date: <input type="date" name=""/>
End Date: <input type="date" name=""/>
I want when i add for example 03/12/2014 in the first field to autoinsert 7 days after the added date into the 2nd field ( in this case it will be 10/12/2014).
I will make my question more clear.
<title>Ha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery.min.js" type="text/javascript" ></script>
<script src="jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
$(function() {
$( "#datepicker1" ).datepicker();
});
</script>
I use jquery datepicker calendar.
And here are my fields:
<div class='ddate'><p>Start date:<input type="date" id="datepicker" name="d1" required="required"></p></div>
<div class='ddate'><p>End date:<input type="date" id="datepicker1" name="d2" ></p></div>
So i should use some JS function or ?
Doing date math in Javascript is hard because the native Date object in Javascript is one of the more poorly implemented objects in the language. My goto date library is moment.js.
The below code should get you pretty close and show you how to validate the fields for invalid date strings.
var $startDate = $('#startDate'),
$endDate = $('#endDate');
$startDate.on('change', function(e) {
var currentDate = moment($(this).val(), "YYYY-MM-DD");
$startDate.css('background', 'none');
if (currentDate.isValid()) {
var weekLater = currentDate.add(7, 'days');
$endDate.val(weekLater.format('YYYY-MM-DD'));
} else {
$startDate.css('background', 'red');
}
});
EDIT:
Working example http://jsbin.com/puwaco/1/edit?html,js,output
If you are using jQuery, you can simply attach an on event when start date changes ...
Start Date: <input type="date" name="date" id="start_date" />
End Date: <input type="date" name="date" id="end_date" />
... then ...
$("#start_date").on('blur', function() {
var self = this;
var new_date = new Date($(self).val());
new_date.setDate(new_date.getDate() + 8);
$("#end_date").val(new_date.yyyymmdd());
});
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
See jsFiddle

Validation with KendoUI datetime

Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.

Categories