Jquery Datepicker with MVC - Get date picked - asp.net-mvc

I have the following in my MVC View:
#Html.TextBoxFor(model => model.FromDateCollected, new { style = "width:90px;" })
In query I have the following:
$("#FromDateCollected").datepicker();
To get the selected date, I tried the following:
var dt = $("#FromDateCollected").datepicker("getDate")
alert(dt);
but getting:
[object Object]

just get the value of text box
var dt = $("#FromDateCollected").val();
alert(dt);
If you want to get the selected date, when user select a date in the calendar, you can do that on the onSelect event
$(function() {
$('#FromDateCollected').datepicker({
onSelect: function(dateText, inst) {
alert(dateText);
}
});
});
Working sample http://jsfiddle.net/pDmjm/5/
EDIT : as per the comment,
$("#FromDateCollected").datepicker("getDate") will give you a Date object and $("#FromDateCollected").val(); will give you a string with current value in the textbox. write the result to a console and you will see the result.
Sample : http://jsfiddle.net/pDmjm/14/ (check firebug console after alerts)

You can get the date from the textbox value.
var dt = new Date(Date.Parse($('#FromDateCollected').val()));
alert(dt);

Related

Displaying a human readable date time in angular js that comes from rails backend

I want to show human readable date time in my frontend. My data comes from rails backend. When I use {{ item.created_at }} it shows the time like rails way 2016-10-10T10:29:47.993Z. But How can I show this like 5 days ago, 3 hours ago in angular js?
To format dates in angular you can use date filter like this:
{{ item.created_at | date:'yyyy-MM-dd HH:mm' }}
You are looking for a very particular format so I think you need to build a custom filter to show exactly that. You can use this filter scaffolding:
.filter('customDate', function() {
return function(date) {
// 1. Get current date
// 2. Get diff from expression date to current
// 3. Apply your format and return result;
};
});
Lastly there is a library called momentjs to manipulate dates and times and there is an angular version of that:
Check the am-time-ago directive of the library:
<span am-time-ago="item.created_at"></span>
Try this, Create a filter for that, for reusability of code
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope){
$scope.date = "1992-05-07T22:00:00.000Z";
});
jimApp.filter('dateFilter', function() {
function calculateDate(date) {
date = new Date(date);
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
return day+'-'+month+'-'+year;
}
return function(date) {
return calculateDate(date);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<div>{{date | dateFilter}}</div>
</div>

Get selected option in Select2 event, when multiple options can be selected

How can I get hold on the <option> that was just selected when listening to the select2:select event? Note that this is simple when using a single-select, as when only one option is selected, that must be the one that was just selected. I would like to also be able to find the option that was just selected when using a multiple-select (<select multiple>).
In the select2:unselect event, the unselected <option> is available through e.params.data.element, but it is not so in the select2:select event. I do not see a reason why the <option> should not be available, since it is created at this time. For the select2:selecting event, however, the <option> is not yet created, and obviously cannot be available when the event is fired.
I've used the following to get the current selected in Select2 (it's for version 4 and up):
// single value
var test = $('#test');
test.on("select2:select", function(event) {
var value = $(event.currentTarget).find("option:selected").val();
console.log(value);
});
UPDATE: Multi Selected Values (with and without last selected)
// multi values, with last selected
var old_values = [];
var test = $("#test");
test.on("select2:select", function(event) {
var values = [];
// copy all option values from selected
$(event.currentTarget).find("option:selected").each(function(i, selected){
values[i] = $(selected).text();
});
// doing a diff of old_values gives the new values selected
var last = $(values).not(old_values).get();
// update old_values for future use
old_values = values;
// output values (all current values selected)
console.log("selected values: ", values);
// output last added value
console.log("last added: ", last);
});
$('#test').on('select2:select', function(e) {
var data = e.params.data;
console.log(data);
});

Very odd event behaviour for onChange on Telerik MVC DatePicker

To the question started, my code (I'll try to only include relevant portions to start), starting with my script:
function RaceDate_onChange() {
var pickedDate = $(this).data('tDatePicker').value();
var month = pickedDate.getMonth() + 1;
$.get("/RaceCard/Details?year=" + pickedDate.getFullYear() + "&month=" + month + "&day=" + pickedDate.getDate());
}
Then my markup:
#Html.Telerik().DatePickerFor(model => model.RaceDate).ClientEvents(events => events.OnChange("RaceDate_onChange"))
And finally a bit of the receiving action:
[HttpGet]
public ActionResult Details(int year, int month, int day)
{
var viewModel = new RaceCardModel {Metadata = DetailModelMetadata.Display, RaceDate = new DateTime(year, month, day)};
I'm trying to get the selection of a new date to trigger a GET, to refresh the page without submitting a form. This works fine, except for this problem:
In GET requests to the Details action, the day value is always one day behind the DatePicker. E.g. The first value is set from a view model property, when the view is rendered, say 3. I then click on 14 and hit my breakpoint in the action method. The day value is 3. When I click on 29 and hit the breakpoint, the day value is 14.
Besides asking what is wrong, I'll take a liberty and ask if there is a better way that is no more complicated. I am fairly novice and would rather deliver working code that needs revision than get bogged down in tangents and details.
Try using e.value instead as shown in the client-side events example. You are probably using an older version where the value() method returned the previous value during the OnChange event.
UPDATE:
"e.value" means the value field of the OnChange arguments:
function onChange(e) {
var date = e.value; // instead of datePicker.value()
}
As far as the 1 month difference you are getting, that's normal, and it is how the getMonth() method works in javascript on a Date instance:
The value returned by getMonth is an
integer between 0 and 11. 0
corresponds to January, 1 to February,
and so on.
So adding +1 is the correct way to cope with the situation, exactly as you did.
Just a little remark about your AJAX call: never hardcode urls. Always use url helpers when dealing with urls:
var year = pickedDate.getFullYear();
var month = pickedDate.getMonth() + 1;
var day = pickedDate.getDate();
var url = '#Url.Action("Details", "RaceCard")';
$.get(url, { year: year, month: month, day: day }, function(result) {
// process the results of the AJAX call
});

jquery ui datepicker

what does navigationAsDateFormat do?
also, I have changeMonth and changeYear enabled, how can I make it so that when you change the month and year using those dropdowns, the input field is automatically updated (e.g., updates without having to click on a new day)
added this parameter, does what I need it to, but would still like to get the day in the easiest way possible:
onChangeMonthYear: function(year, month, inst) { $(this).val(month + '/01/' + year); }
Here's the docs for navigationAsDateFormat
When true the formatDate function is
applied to the prevText, nextText, and
currentText values before display,
allowing them to display the target
month names for example.
You could write a function to change the value in the input when the onChangeMonthYear event is raised
Here's a Working Demo
Something like
$('#picker').datepicker({
onChangeMonthYear: function(year, month, inst) {
var now = new Date(this.value);
if (now) {
var max = new Date(year, month, 0).getDate();
var day = now.getDate() > max?
max : now.getDate();
var newDate = new Date(year, month -1, day);
inst.input.datepicker('setDate', newDate);
}
},
changeMonth: true,
changeYear: true
});

jQuery UI Datepicker - How can i, on select, highlight a particular range of dates?

I want to, when the user selects a date, highlight the following 11 days. The intention is to show a 12-day range selected depending on whatever day was chosen.
I've seen the "date range picker" from http://www.filamentgroup.com/ suggested, but this doesnt really give me the visualization i want, it just lets a user pick a range (from/to) as i understand it.
Any suggestion on how i can realize this?
Cheers
You can use the beforeShowDay event to give a CSS style for the dates you need to highlight.
Code:
$(document).ready(function(){
var selected = null;
$('#datePicker').datepicker({beforeShowDay: function(date) {
if (selected != null && date.getTime() > selected.getTime() &&
(date.getTime() - selected.getTime()) < 12*24*3600*1000) {
return [true, "highlighted"];
}
return [true, ""];
}});
$("#datePicker").datepicker( 'option' , 'onSelect', function() {
str = $(this).val().toString();
selected=$.datepicker.parseDate('mm/dd/yy', str);
console.log(selected);
});
});

Resources