Bootstrap Date Paginator datepicker - javascript

I would like to make redirect when a date is changed and transmit selected date parameter (via window.location.href). I'm using Bootstrap Date Paginator, which contains Bootstrap datepicker, but I don't know how to change these lines of code to work properly:
this.$calendar
.datepicker({
options...
})
.datepicker('update', this.options.selectedDate.toDate())
.on('changeDate', $.proxy(this._calendarSelect, this));
I know I would use changeDate event but there aren't any examples of using this event. Can you help me, please?

Would this do?
You can use .on('change', ..) like this,
this.$calendar
.datepicker({
options...
}).on('change', function() {
var changedDate = this.$calendar.val();
//alert("value of date is "+ x);
var theUrl = 'your URL';
window.location.href = theUrl+"date="changedDate
});
Else use, on('change.dp', ..) event like this,
this.$calendar
.datepicker({
options...
}).on('change.dp', function() {
var changedDate = this.$calendar.val();
//alert("value of date is "+ x);
var theUrl = 'your URL';
window.location.href = theUrl+"date="changedDate
});
Alternatively have a look at this too.

May be it's too late, but I have same problem and come up with this solution,
while setting options for Bootstrap Date Paginator keep track of onSelectedDateChanged function and assign the date value to a variable and send that variable to location.href.
<script>
var currDate = new Date();
var options = {
selectedDateFormat: 'DD/MM/YYYY',
selectedDate: moment(currDate).format('DD/MM/YYYY'),
onSelectedDateChanged: function (event, date) {
var dateSelected = moment(date).format('DD/MM/YYYY');
location.href = '/ServletName?timestamp='+currDate .getTime() + "&date=" + dateSelected ;
},
};
$('#paginator').datepaginator(options);
</script>
<body>
<div id="paginator"></div>
</body>

Related

How to check when input value is changed?

How can i check when a value on input is changed.
I have a calendar and when i click on calendar it changes the value on input , but when im trying to see if it has changed its not working. i have tried AddEventListener, also jquery on change, also i sent a function on change to call it but none of them is working.
<input type="text" id="date" class="date" onchange="changed()" name="" >
function changed(){
alert("hello world");
}
Main js file for creating the calendar :
This function creates the calendar on my php file .
And then when on click it gets the value on the input with id #date
But When im trying to see if value has changed it is not working .
// Initialize the calendar by appending the HTML dates
function init_calendar(date) {
$(".tbody").empty();
$(".events-container").empty();
var calendar_days = $(".tbody");
var month = date.getMonth();
var year = date.getFullYear();
var day_count = days_in_month(month, year);
var row = $("<tr class='table-row'></tr>");
var today = date.getDate();
// Set date to 1 to find the first day of the month
date.setDate(1);
var first_day = date.getDay();
// 35+firstDay is the number of date elements to be added to the dates table
// 35 is from (7 days in a week) * (up to 5 rows of dates in a month)
for(var i=0; i<35+first_day; i++) {
// Since some of the elements will be blank,
// need to calculate actual date from index
var day = i-first_day+1;
// If it is a sunday, make a new row
if(i%7===0) {
calendar_days.append(row);
row = $("<tr class='table-row'></tr>");
}
// if current index isn't a day in this month, make it blank
if(i < first_day || day > day_count) {
var curr_date = $("<td class='table-date nil'>"+"</td>");
row.append(curr_date);
}
else {
var monthplusone = months[month];
var curr_date = $("<td class='table-date' id='"+day+"-"+monthplusone+"-"+year+"'>"+day+"</td>");
var events = check_events(day, month+1, year);
if(today===day && $(".active-date").length===0) {
curr_date.addClass("active-date");
let x = document.getElementById('date').value=day+"-"+monthplusone+"-"+year;
$('.table-date').ready(function () {
x.value;
});
show_events(events, months[month], day);
}
// If this date has any events, style it with .event-date
if(events.length!==0) {
curr_date.addClass("event-date");
}
// Set onClick handler for clicking a date
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
curr_date.click({events: events, month: months[month], day:day}, date_click);
row.append(curr_date);
}
}
// Append the last row and set the current year
calendar_days.append(row);
$(".year").text(year);
}
Notice that change is actually triggered when the input is not focused anymore.
document.getElementById("date").addEventListener("change", function () {
alert("hello world");
});
<input type="text" id="date" class="date" name="">
This works. Not sure where you're running into an issue.
function changed(){
console.log("hello world");
}
<input type="text" id="date" class="date" onchange="changed()" name="" >
EDIT: Shortened version of init_calender() for others interested in answering:
function setDate() {
document.getElementById("date").value = '19-Dec-2021'
}
I basically agree with #Spankied in that you should try and shorten your code to the point where you are having the issue. However, after looking at your code it seems to me that you want the following function
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
to not only change the value in your #date input but also trigger its change event-handler function. You can do that by changing it to something like
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
$("#date" ).change();
});
jQuery.change() without any arguments will trigger a predefined "change"-event on the DOM-object that is selected by the jQuery-object.
You can use js to do that:
let x = $(...) //select the input box
let val = x.value;
function repeat() {
if (val !== x.value) {
change()
}
}
setInterval(repeat, 100)
This checks if the result is the same.
This might make your site a bit slow and it might look odd but this will work in just every case
<script>
let Oldvalue = $('.date')[0].val();
setInterval(() => {
let currentValue = $('.data')[0].val()
if (Oldvalue != currentValue){
//do whatever but in end write this
Oldvalue = currentValue;
}
}, 10);
</script>

Bootstrap Datepicker and Disable C#/JSON array of dates,

I have a list of dates that I want to disable in my bootstrap date picker. I cannot get the datesDisabled function to work with the array of dates returned from JSON. It does work with a hard coded array of dates.
Is there something that I need to do format the dates returned from JSON in order to get it to work?
Query:
var DatesBooked= JsonConvert.SerializeObject(db.Calendar.Where(x => x.CalLocation != "OFF")).Select(x => x.CalDate).Distinct().ToList());
In my view:
#Html.TextBox("AddedDates", null, new { #class = "form-control small", #Value = ViewBag.SelDate, autocomplete = "off" })
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.timepicker.js"></script>
<script src="~/Scripts/bootstrap-datepicker.min.js"></script>
<script>
var unavailableDates= #Html.Raw(Json.Encode(Model.DatesBooked));
$input = $("#AddedDates");
$input.datepicker({
multidate: true,
multidateSeparator: ',',
datesDisabled: unavailableDates,
});
</script>
unavailableDates value
var unavailableDates = "[\"2016-05-01T00:00:00\",\"2016-05-02T00:00:00\",\"2016-05-03T00:00:00\",\"2016-06-24T00:00:00\",\"2016-06-25T00:00:00\"]"
If I hardcode thisfor unavailableDates, everything works fine.
var unavailableDates = ["05/25/2016", "05/26/2016"]
How do I need to format the dates in order to get this to work?
TIA!
Well after many attempts and more research, I was able to solve this by doing the following:
I reformatted the date using C#:
var checkdates = db.Calendar.Where(x => x.CalLocation != "OFF")).Select(x => x.CalDate).Distinct().ToList()
var DatesBooked= JsonConvert.SerializeObject(checkdates, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "MM/dd/yyyy" });
Then in the view, I stripped the "\" characters returned by JSON and created an array:
var unavailableDates = #Html.Raw(Json.Encode(Model.DatesBooked));
var formatDates = unavailableDates.replace(/\\/g, "");
var trimDate = formatDates.slice(1, -1); // to remove " at beginning and end
var finalDates = JSON.parse("[" + trimDate + "]");
$input = $("#AddedDates");
$input.datepicker({
multidate: true,
multidateSeparator: ',',
datesDisabled: finalDates,
todayHighlight: true
});

JQuery Values are not changing

#Html.ActionLink("Search", "GetDateWiseGuestReport", "Reports", new { StartDate = "sss",EndDate="eee" }, new { #id = "btnDateWiseGuestSearch", #class = "btn btn-red" })
$("#btnDateWiseGuestSearch").bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = this.href.replace("sss", StartDate);
this.href = this.href.replace("eee", EndDate);
});
Okay i am using above code to change the Action-link URL at run time.Everything is running smoothly. but i have a strange issue i.e. when i click the button 1st time its gets the values from text boxes and change accordingly, but when i press button again its doesn't get new values from text boxes rather its somehow using OLD VALUES that i inputted 1st time!
Because after the firs click you are replacing the sss and eee from the href so there after is no sss or eee in the href. So nothing is replaced after the first click
So a possible solution is to store the original href value somewhere else then use that for replacing the content. In the below solution the data api is used to store the original value
var $btn = $("#btnDateWiseGuestSearch");
$btn.data('href', $btn.attr('href'))
$btn.bind('click', function () {
//Get the id of the selected item in dropdown
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
var href = $(this).data('href');
this.href = href.replace("sss", StartDate).replace("eee", EndDate);
});
Basically in your jQuery code you are create a new link by replacing sss and eee however once you have replaced them that is it, you won't find them again
this.href = this.href.replace("sss", StartDate); // sss no longer exists after this
this.href = this.href.replace("eee", EndDate); // sss no longer exists after this
What you will need to do is store the original href value before you modify it and then reference that when you want to update the link
$("#btnDateWiseGuestSearch").bind('click', function () {
var $this = $(this);
var originalhref = $this.data("href");
if(!originalhref){
this.data("href", this.href);
}
var EndDate = $("#txtDateWiseGuestEndDate").val();
var StartDate = $("#txtDateWiseGuestStartDate").val();
this.href = originalhref.replace("sss", StartDate).replace("eee", EndDate);
});

jQuery - Bootstrap Datepicker onChange issue

I am trying change link when a date is selected but whenever I select a date, I get
?day= Here's my code:
Markup:
<i class="icon-calendar"></i>
It only works when I use input
<input type="text" class="datepicker">
Javascript:
$(document).ready(function(){
$(".datepicker").datepicker({
format: "yyyy-mm-dd",
endDate: "-2d"
})
.on('changeDate', function(ev){
var dateData = $('.datepicker').val();
window.location.href = "?day=" + dateData ;
});
});
Expected results: ?day=2013-11-01
Thanks
According to the documentation you can get the formatted date with the format() function accessible through the event object:
$(document).ready(function(){
$(".datepicker").datepicker({
format: "yyyy-mm-dd",
endDate: "-2d"
})
.on('changeDate', function(ev){
window.location.href = "?day=" + ev.format();
});
});
I'm pretty sure you can access the date via ev:
$(document).ready(function(){
$(".datepicker").datepicker({
format: "yyyy-mm-dd",
endDate: "-2d"
})
.on('changeDate', function(ev){
var dateData = new Date(ev.date); // this is the change
window.location.href = "?day=" + dateData ;
});
});
I have not tested it but I think it should be more like
$(".datepicker").on('change', function(ev){
var dateData = $(this).val();
window.location.href = "?day=" + dateData ;
});

making auto-updating, facebook-style time formatting

Can some help me figure out why my javascript HTML template doesn't auto-update the time but the regular HTML does? Here's the templating library i'm using: https://github.com/blueimp/JavaScript-Templates
here's my JS (you can fiddle with it here: http://jsfiddle.net/trpeters1/SpYXM/76/ ):
$(document.body).on('click', 'button', function(){
var id= $(this).data('id');
var data={id:id, string: "just now...", fxn: nicetime()};
var result = tmpl('<div id="string" data-id="'+id+'">{%=o.string%}</div><div id="function" data-id="'+id+'">{%=o.fxn%}</div>', data);
$('div[data-id="'+id+'"]').html(result);
nicetime();
});
function nicetime(){
var time = new Date(),
var comment_date = setInterval(function() {
var time2 = time_since(time.getTime()/1000);
$('#time_since').html(time2);
return time2;
},
1000);
}
HTML:
<button data-id="1">1</button>
<div data-id="1"></div> //tmpl output
<div id="time_since"></div> //non-tmpl output
You want something like this.
With JavaScript templating, you generally want to template once, then update the values of specific elements dynamically, as opposed to resetting the innerHTML of an entire element every second.
Here's the JavaScript:
$(document.body).on('click', 'button', function(){
var id= $(this).val(),
time = +new Date,
data = {
id: id,
string: "just now..."
},
result = tmpl('<span class="string">{%=o.string%}</span>', data),
tgt = $('#'+id),
str;
tgt.html(result);
str = tgt.find('.string');
window.setInterval(function() {
str.html(time_since(time/1000));
}, 1000);
});

Categories

Resources