Is it possible to bind to a knockout property to options datepickerOptions - asp.net-mvc-3

http://jsfiddle.net/jmogera/g9cNL/1/
I have posted this example on what I am trying to do. I basically want to bind to the datapickeroptions with a knockout property. I want to change the minDate as certain flag is set to true.
<input data-bind="datepicker: myDate, datepickerOptions: { minDate: date }" />
var viewModel = {
date: ko.observable(new Date()),
myDate: ko.observable(new Date("09/01/2011")),
setToCurrentDate: function() {
this.myDate(new Date());
}
};
Is this possible?

Yes.
Inside the custom binding use just use the allBindingAccessor
var allBindings = allBindingAccessor();
var dateOptions = allBindings.datePickerOptions;
var minDate = dateOptions.minDate;

Related

Kendo Grid Filtering a dataSource

I have a grid bound to a simple object. There are no Ajax calls. It's all set at init.
My Object: Account with properties Name and an Array of Tag strings. Real simple.
I pass in an array of tags into this function and need the dataSource to filter the grid. How is that done?
function filterGridResults(tags) {
var grid = $("#gridAccounts").data("kendoGrid");
var dataSource = grid.dataSource;
//??? filter document.Tags
}
If I understand you correctly you are binding your grid to local data. If so then this should solve your problem:
function filterGridResults(tags) {
var grid = $("#gridAccounts").data("kendoGrid");
var dataSource = grid.dataSource;
var filterField = "Tag";//This is the object field you will filter by
var filterOperator = "contains";//How you will filter
var filterValue = tags;//What your filter value will be
dataSource.filter(
{
field: filterField,
operator: filterOperator ,
value: filterValue
});
}
Hope this answers your question!

Knockout predefined default with options binding to observable array

I am getting a list of options for a select from a server and populating an observableArray. Then I would like to set the selected item to a predefined value. I have a very simple jsFiddle that emulates pulling data from a server with a button click.
http://jsfiddle.net/JonathanN/hev1rqeu/
Here's the Javascript with the basic attempt:
(function() {
var vm = (function() {
var self = this;
self.array = ko.observableArray([]);
self.selectedValue = ko.observable();
self.useSetTimeout = ko.observable(false);
self.array.subscribe(function(newValue) {
self.selectedValue('b');
});
self.populate = function() {
self.array(['a','b','c']);
};
}());
ko.applyBindings(vm);
}());
And here's my workaround, which replaces "self.selectedValue('b');":
var waitForSelectToPopulate = function() {
self.selectedValue('b');
if(self.selectedValue() != 'b') {
setTimeout(waitForSelectToPopulate, 10);
}
};
waitForSelectToPopulate();
I am not very fond of this as a workaround. It seems like there should be a reasonable way to handle this, but just setting the value on subscribe trigger doesn't seem to work.
You need optionsAfterRender. Here's a fiddle:
http://jsfiddle.net/sifriday/hev1rqeu/4/
HTML -
<select data-bind="options: array, value: selectedValue, optionsAfterRender: setVal">
JS addition -
self.setVal = function() {
self.selectedValue('b');
}
Docs - http://knockoutjs.com/documentation/options-binding.html - and scroll down to Note 2
Once the populate event has gone and got the json and placed it into your array, why not just set the value right after? as soon as you set the data inside of self.array it will update.
(function() {
var vm = (function() {
var self = this;
self.array = ko.observableArray([]);
self.selectedValue = ko.observable();
self.populate = function() {
// magical assmagic goes and get's json, and converts it to ['a','b','c']
self.array(['a','b','c']); // dropdown is now populated
self.selectedValue('c'); // therefore we can set it to a valid value
};
}());
ko.applyBindings(vm);
}());
see the following:
http://jsfiddle.net/hev1rqeu/5/

Remote update cell content in kendo grid

Here I have a code to update a cell contet when pressing a button.
It works fine, but it doesn't set the flag, that indicates, that the cell has been changed.
It should look like this with the litle red triangle:
The code:
<a id="button" href="#">Click me</a>
<div id="grid"></div>
<script>
var dataSource, grid;
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
data: [
{ category: "Beverages", name: "Chai", price: 18},
{ category: "Seafood", name: "Konbu", price: 6}
],
})
grid = $("#grid").kendoGrid({
dataSource: dataSource,
editable: true,
}).data("kendoGrid");
$('#button').click(function (e) {
var data = grid.dataItem("tr:eq(1)");
data.set('category', 'Merchandice');
});
});
</script>
Update:
Here is the update based on #tstancin: Kendo example.
Thank you for the answer - I had thought of it to.
I am wondering if it's possible to do the update in a more clean way with some binding through som MVVM perhaps?
Kind regards from Kenneth
If that's all you want then you should expand your button click code with the following:
$('#button').click(function (e) {
var data = grid.dataItem("tr:eq(1)");
data.set('category', 'Merchandice');
$("#grid tr:eq(1) td:eq(1)").addClass("k-dirty-cell");
$("#grid tr:eq(1) td:eq(0)").prepend("<span class='k-dirty'></span>");
});
But if you, for instance, manually change the value of name column from Chai to something else, and then click the click me button, the dirty marker in the name column will disappear.
You should use flags for every cell and set them before data.set(). Then, in the grid's dataBound event you should inspect every cell's value and assign the dirty marker if it's needed. For manual changes you should handle the save event and set flags there.
I wrote a script that makes it posible to use a call like this:
SetCellData(id, columnName, value);
So with an id, a columnName and a value, I can update a value in a grid and the flag will be set on the cell.
function SetCellData(id, columnName, value) {
var dataItem = grid.dataSource.get(id);
dataItem.set(columnName, value);
var columnIndex = GetColumnIndex(columnName);
if (columnIndex > -1) {
var cell = $('tr[data-uid*="' + dataItem.uid + '"] td:eq(' + columnIndex + ')')
if (!cell.hasClass("k-dirty-cell")){
cell.prepend("<span class='k-dirty'></span>");
cell.addClass("k-dirty-cell");
}
}
}
function GetColumnIndex(columnName) {
var columns = grid.columns;
for (var i = 0; i < columns.length; i++)
if (columns[i].field == columnName)
return i;
return -1;
};
I have the code here : example

datepicker JQuery Validations and Format

I am using the following for datepicker in Jquery to format the date display in dd/mm/yy format and also I want the user not to select future date.Only one thing is working at a time.
<script type="text/javascript" language ="javascript" >
$(function () {
var date = new Date();
var currentDate = date.getDate();
var currentMonth = date.getMonth();
var currentYear = date.getFullYear();
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
$(".datepicker").datepicker({ maxDate: new Date(currentYear, currentMonth, currentDate) });
});
</script>
How do make, both the dateformat and disable the future dates to work simultaneously. I am missing single bit, I don't know how to club this two validations or requirements togather.
Any answers Please?
Thank you.
I had a similar requirement for my code with a hire date. Here's how I did it:
$('#hireDate').datepicker({
dateFormat: 'dd/mm/yy',
maxDate: new Date(currentYear, currentMonth, currentDay)
});
The user can still enter a future date manually and weasel around your date picker. We had this problem on a production system.
If you want to additionally validate the date using the validation plugin, try this:
/**
* Requires Datepicker and Validator
*
* Params:
* 0...dateformat. see datepicker
* 1...date. Value "0" is "today"
* 2...(optional). date to display. will be automatically filled if 0 and 1 are set.
* usage:
* myfield: { maxDate: ['m/d/yy', 0] }
*/
jQuery.validator.addMethod("maxDate",
function(value, element, params) {
if (!params[0])
throw 'params missing dateFormat';
if (typeof(params[1]) == 'undefined' )
throw 'params missing maxDate';
var dateFormat = params[0];
var maxDate = params[1];
if (maxDate == 0) {
maxDate = new Date();
maxDate.setHours(0); // make it 00:00:0
maxDate.setMinutes(0);
maxDate.setSeconds(0);
maxDate.setMilliseconds(0);
}
if (typeof(params[2]) == 'undefined' )
params[2] = $.datepicker.formatDate(dateFormat, maxDate);
try {
var valueAsDate = $.datepicker.parseDate( dateFormat, value )
return (valueAsDate < maxDate);
} catch (x) {
return false;
}
},'Must be greater than {2}.');
$("#myform").validate({
rules: {
datepicker : {
maxDate ['m/d/yy', 0]
}
}
});
HTML:
<input name="datepicker" class="datepicker" type="text"/>

Jquery bassistance: validate that end date is after start date

I am using jquery bassistance validation and need to verify that a start date is after an end date. I am wondering if anyone knows if this functionality exists and if I can add rules to do this or if I have to add a custom check. I am having difficulty finding any examples of this that work with my code which forwards to another function if the form is valid. (pasted below)
$("#hotels").validate({
rules: {
checkinDate: {
date: true
},
checkoutDate: {
date: true
}
}
});
$("#hotels input.submit").click(function() {
var isValid = $("#hotels").valid();
if (isValid == true) {
} else {
hComp();
return false;
}
} else {
return false;
}
});
I saw this in another example, but am not sure how I could use it.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
Thanks in advance for any assistance.
That example looks like it's exactly what you need. Have a look here.
Borrowing from that jquery example, suppose you have the following HTML:
<input id="startDate" value="Jan 12, 2009" />
<input id="endDate" value="Jan 12, 2010" />
Then this JavaScript code should show the alert "Start date is before end date!" (assuming the values aren't modified):
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
alert("Start date is before end date!");
}
I ended up solving this problem before validation, which is probably a much better idea anyway. Here's the solution using the jquery ui datepicker. Then I can just use the same logic to do a final validation check.
$('input').filter('.datepicker').datepicker({
beforeShow: customRange,
showOn: 'both',
buttonImage: contextPath + '/assets/images/icon-calendar.gif',
buttonImageOnly: true,
buttonText: 'Show Date Picker'
});
function customRange(a) {
var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
if (a.id == 'checkoutDate') {
if ($('#checkinDate').datepicker('getDate') != null) {
c = $('#checkinDate').datepicker('getDate');
}
}
return {
minDate: c
}
}

Resources