jQueryUI DatePicker Validation - validation

I am trying to validate the date fields so when you if you select a date in the future and in the second input box you select today's date it should not let you submit the form.
I have it working so you cant select yesterday's date - its the date comparison that i cant seem to get working.
/js/jquery-ui-1.8.6.custom.min.js"/>
/js/jquery.validate.js" />
/js/jquery.ui.datepicker.validation.js" />
<asp:TextBox ID="txtStartDate" runat="server" CssClass="DatepickerInput validBeforeDatepicker" />
<asp:TextBox ID="txtEndDate" runat="server" CssClass="DatepickerInput validAfterDatepicker" />
<script type="text/javascript">
$(function () {
$("#tabs").tabs();
});
$('.validBeforeDatepicker,.validAfterDatepicker').datepicker();
$(function () {
$(".DatepickerInput").datepicker({
showOn: "button",
buttonImage: "/assets/img/calendar.gif",
buttonImageOnly: true,
minDate: 0,
required: true,
message: "This is a required field",
dateFormat: 'dd-mm-yy'
});
});
$(function () {
$("#validAfterDatepicker").datepicker({
showOn: "button",
buttonImage: "/assets/img/calendar.gif",
buttonImageOnly: true,
minDate: +1,
required: true,
message: "This is a required field",
dateFormat: 'dd-mm-yy'
});
});
I'm following this example but I'm going wrong somewhere and cant seem to quite put my finger on what it could be.
Website: http://bit.ly/WdZf10
Please dont submit form as it will just be spam if testing the form on the website. You can see its not validating even before submitting the form

Found a fix for the problem and probably less code used for it as well. Thought I'd share so if anyone gets stuck they can use this.
<script type="text/javascript">
$(function () {
function getDiff() {
var from = $(".start").val();
var till = $(".fin").val();
var c = from.split("/");
beg = new Date(c[2], c[1] - 1, c[0]);
var d = till.split("/");
en = new Date(d[2], d[1] - 1, d[0]);
var rest = (en - beg) / 86400000;
var txt = rest == 0 ? "" : rest + " days"
$("#res").text(txt);
}
$(".start").datepicker({
changeMonth: false,
changeYear: false,
showAnim: "fadeIn",
gotoCurrent: true,
minDate: 0, //change this to +3 to start 3 days from now
dateFormat: "dd/mm/yy",
onSelect: function (dateText, inst) {
$(".fin").val(dateText);
$(".fin").datepicker("option", "minDate", dateText);
getDiff();
}
});
$(".fin").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
showAnim: "fadeIn",
onSelect: getDiff
});
});

Related

Data doesn't refresh on clicking on next button on Jqgrid

<script language="javascript" type="text/javascript" src="/SiteAssets/test%20js/jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/JqLib/i18n/grid.locale-en.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/JqLib/jquery.jqGrid.min.js"></script>
<script language="javascript" type="text/javascript" src="/SiteAssets/JqLib/jquery.SPServices-0.7.2.min.js"></script>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json2/20150503/json2.min.js"></script>
<link rel="stylesheet" href="/SiteAssets/styles/ui.jqgrid.css">
<link rel="stylesheet" href="/SiteAssets/styles/ui-lightness/jquery-ui-1.7.3.custom.css">
<script language="javascript" type="text/javascript">
$(document).ready(function() {
debugger;
jQuery("#list").jqGrid({
datatype: GetMyData,
colNames:["ID","Title","Description"],
colModel:[{name:'ID',index:'ID',align:'left',sortable: true,width:"1500px"},
{name:'Title',index:'Title',align:'left',sortable: true, width:"1500px"},
{name:'Description',index:'Description',align:'left',sortable:true, width:"1500px"},],
pager: true,
pager: '#pager',
pageinput: true,
rowNum: 5,
rowList: [5, 10, 20, 50, 100],
sortname: 'ID',
sortorder: "asc",
viewrecords: true,
autowidth: true,
emptyrecords: "No records to view",
loadonce: true,
loadtext: "Loading..."
});
jQuery("#list").jqGrid('navGrid', "#pager", { edit: false, add: false, del: false, search: true, refresh: true }); });
function GetMyData(){
var ex='e';
Query="<Query><Where><Or><Contains><FieldRef Name='Title'/><Value Type='Text'>"+ex+"</Value></Contains><Contains><FieldRef Name='Description' />"+"<Value Type='Text'>"+ex+"</Value></Contains></Or></Where></Query>";
var CAMLViewFields="<ViewFields><FieldRef Name='Title'/><FieldRef Name='Description'/> <FieldRef Name='ID'/></ViewFields>";
GetDataOnLoad(Query, CAMLViewFields);
}
function GetDataOnLoad(Query, CAMLViewFields) {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "List1",
CAMLQuery:Query,
CAMLViewFields:CAMLViewFields ,
completefunc: processResult
});
}
function processResult(xData, status) {
var counter = 0;
var newJqData = "";
debugger;
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var JqData;
if (counter == 0) {
JqData="{"+'"id"'+":"+'"'+$(this).attr("ows_ID")+'",'+'"cell"'+":["+'"'+$(this).attr("ows_ID")+'",'+ '"'+$(this).attr("ows_Title")+'",'+ '"'
+$(this).attr("ows_Description")+'"'+"]}";
newJqData = newJqData + JqData;
counter = counter + 1;
} else {
var JqData="{"+'"id"'+":"+'"'+$(this).attr("ows_ID")+'",'+'"cell"'+":["+'"'+$(this).attr("ows_ID")+'",'+ '"'+$(this).attr("ows_Title")+'",'
+ '"'+$(this).attr("ows_Description")+'"'+"]}";
newJqData = newJqData +","+ JqData;
counter = counter + 1;
}
});
FinalDataForGrid(newJqData, counter);
}
function FinalDataForGrid(jqData, resultCount) {
debugger;
dataFromList = jqData.substring(0, jqData.length - 1);
var currentValue = jQuery("#list").getGridParam('rowNum');
var totalPages = Math.ceil(resultCount / currentValue);
var PageNumber = jQuery("#list").getGridParam("page"); // Current page number selected in the selection box of the JqGrid
newStr = "{"+'"total":'+'"'+totalPages+'",'+'"page":'+'"'+PageNumber+'",'+'"records":'+'"'+resultCount+'",'+'"rows":['+dataFromList+ "}]}";
var thegrid = jQuery("#list")[0];
var obj=JSON.stringify(newStr);
thegrid.addJSONData(JSON.parse(newStr));
}
</script>
<table id="list" width="100%" ></table>
<div id="pager" style="text-align:center;"></div>
I want to display data from SharePoint List using CAML Query, SPServices and JQGrid.
The data gets binded to the grid, I can see Page 1 of 2 and View 1-5 of 10. But When I click on next button, then Page 2 of 2 shows and view 6-10 of 10 shows up but data doesnt change. I am new to jqgrid, faced many issues even to bind grid, all are resolved right now except for pagination.

How to disable the cell if the date is empty or null or undefined?

I'm new to jqgrid and jquery, can someone please help me in disabling the cell when the date is null or empty or undefined?
Actually the json for some (rows,col) date data is there and for some it is not there.
I want to disable the cell in the row for which Date data is not available.
grid cell editing POC
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="/jqGrid/jquery-ui-1.11.4.custom/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/jqGrid/Guriddo_jqGrid_JS_5.0.1/css/ui.jqgrid.css">
<script type="text/ecmascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/jqGrid/jquery-ui-1.11.4.custom/jquery-ui.min.js"></script>
<script type="text/javascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="/jqGrid/Guriddo_jqGrid_JS_5.0.1/src/jquery.jqGrid.js"></script>
<script type="text/javascript">
$(function () {
"use strict";
var grid = $("#tree");
var initDateWithButton = function (elem) {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
if (grid.jqGrid('getCell',id,'assignedDate') == null) {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
if (grid.jqGrid('getCell',id,'assignedDate') == "") {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
if (grid.jqGrid('getCell',id,'assignedDate') == undefined) {
grid.jqGrid('setCell',id,'assignedDate','','not-editable-cell');
}
}
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
showWeek: false,
showButtonPanel: true,
buttonImage: 'http://rcban0015:10039/GridPOC/pages/calenderIcon.gif',
onClose: function (dateText, inst) {
inst.input.focus();
}
});
$(elem).next('button.ui-datepicker-trigger').button({
text: false,
position: "relative",
top: "4px"
});
}, 100);
},
dateTemplate = {align: 'center', sorttype: 'date', editable: true,
formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, datefmt: 'd-M-Y',
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
size: 11, // for the advanced searching dialog
attr: {size: 11} // for the searching toolbar
}},
lastSel;
jQuery('#tree').jqGrid({
url: '<%= webAppAccess.getBackchannelActionURL("actionListjqGridPagination",false) %>',
"colModel":[
{
"name":"course_id",
"index":"course_id",
"sorttype":"int",
"key":true,
"hidden":true,
"width":50
},{
"name":"courseName",
"index":"courseName",
"sorttype":"string",
"label":"courseName",
"width":200
},{
"name":"facility",
"index":"facility",
"label":"facility",
"width":200,
"align":"left"
},{
"name":"assignedDate",
"index":"assignedDate",
"label":"assignedDate",
"width":110,
"template": dateTemplate
},{
"name":"dueDate",
"index":"dueDate",
"label":"dueDate",
"width":110,
"template": dateTemplate
},
{
"name":"AssignmentStatus",
"index":"AssignmentStatus",
"label":"AssignmentStatus",
"width":50
},{
"name":"Action",
"index":"Action",
"label":"Action",
"width":50
},
{
"name":"lft",
"hidden":true
},{
"name":"rgt",
"hidden":true
},{
"name":"level",
"hidden":true
},{
"name":"uiicon",
"hidden":true
}
],
"jsonReader": { "repeatitems": false, "root": "employees.rows" },
"toolbar": [true, "top"],
"width":"1200",
"hoverrows":false,
"viewrecords":false,
"gridview":true,
"height":"auto",
"sortname":"lft",
"loadonce":true,
"rowNum": 2,
"rowList":[2,10,15],
"scrollrows":true,
// enable tree grid
"treeGrid":true,
// which column is expandable
"ExpandColumn":"courseName",
// datatype
"treedatatype":"json",
// the model used
"treeGridModel":"nested",
// configuration of the data comming from server
"treeReader":{
"left_field":"lft",
"right_field":"rgt",
"level_field":"level",
"leaf_field":"isLeaf",
"expanded_field":"expanded",
"loaded":"loaded",
// set the ui icon field froom data
"icon_field":"uiicon"
},
"sortorder":"asc",
"datatype":"json",
"pager":"#pager",
"cellEdit": true, // TRUE = turns on celledit for the grid.
"cellsubmit" : 'clientArray',
"editurl": 'clientArray'
});
$('#t_' +"tree")
.append($("<div><label for=\"globalSearchText\">Global search in grid for: </label><input id=\"globalSearchText\" type=\"text\"></input> <button id=\"globalSearch\" type=\"button\">Search</button></div>"));
$("#globalSearchText").keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
if (key === $.ui.keyCode.ENTER) { // 13
$("#globalSearch").click();
}
});
$("#globalSearch").button({
icons: { primary: "ui-icon-search" },
text: false
}).click(function () {
var postData = jQuery('#tree').jqGrid("getGridParam", "postData"),
colModel = jQuery('#tree').jqGrid("getGridParam", "colModel"),
rules = [],
searchText = $("#globalSearchText").val(),
l = colModel.length,
i,
cm;
for (i = 0; i < l; i++) {
cm = colModel[i];
if (cm.search !== false && (cm.stype === undefined || cm.stype === "text")) {
rules.push({
field: cm.name,
op: "cn",
data: searchText
});
}
}
postData.filters = JSON.stringify({
groupOp: "OR",
rules: rules
});
jQuery('#tree').jqGrid("setGridParam", { search: true });
jQuery('#tree').trigger("reloadGrid", [{page: 1, current: true}]);
return false;
});
});
</script>
</head>
<body>
<table id="tree"><tr><td></td></tr></table>
<div id="pager"></div>
</body>
</html>
There are exist alternative fork of jqGrid: free jqGrid, which I develop since more as one year. It has the functionality, where one can define editable property of colModel as function, which can return true or false based on the cell or the row content. See the wiki article for more details.
Check if this How to disable editing for soe cells in row editing of JQGrid
helps, it seen it is a similar thing, You just need to add into your logic.

jquery ui dialog doesn't work with buttons

I'm trying to show a modal confirm dialog on delete link in a list action of a mvc 3 application.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#dialog-confirm").dialog({
autoOpen: false,
modal: true,
resizable: false,
height: 180
});
});
$(document).delegate(".deleteLink", "click", function (e) {
e.preventDefault();
alert('test');
var $link = $(this);
var $dialog = $('#dialog-confirm')
.dialog({
autoOpen: false,
modal: true,
resizable: false,
height: 180,
buttons: {
'button text': function () {
alert("button"); //this is the button, do something with it :)
}
}
});
$dialog.dialog('open');
});
<div id="dialog-confirm" title="Delete the item?" >
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be deleted. Are you sure?</p>
and this is the link
#Html.ActionLink("حذف", "Delete", "Need", new { id = item.NeedID }, new { #class = "deleteLink", title = "حذف" })
when i remove the buttons option it works but when i add it , it doesn't show up anymore
where i'm doing wrong?
At a very quick glance - it would seem that buttons is an array. Try pasting in the sample from the documentation:
... {
autoOpen: false,
modal: true,
resizable: false,
height: 180,
buttons: [ { text: "Ok", click: function() { $( this ).dialog( "close" ); } } ]
}

Foreignkey field get '[object object]' value when editRow with original field value is null

I have an issue that I use a dropdown list for my foreignkey field like demo : http://demos.kendoui.com/web/grid/foreignkeycolumn.html
The difference is that the foreignkey field in my model which can be null some time if it is not related to anyone else. Then the issue for me is when I try to editRow with this foreignkey field's original value is null, and I want to change to another value, this field will always get the value '[object object]'. I don't know why.
See the floor field in the following code:
<script>
$(document).ready(function() {
var template = kendo.template($("#detail_template").html());
function show_menu_details(menuObj) {
var tg = $("#details");
tg.fadeOut(function(){
tg.html(template(menuObj));
tw = tg.find(".k-window");
tw.css({width:tg.innerWidth()-30, height:tg.innerHeight()-55, "margin-top": 20, "margin-left":15});
});
tg.fadeIn();
}
$("#horizontal").kendoSplitter({
panes: [{collapsible: true, size: "180px"},
{ collapsible: true} ],
height: 690
});
function onChange(e){
e.preventDefault();
selectedObj = this.dataSource.getByUid(this.select().data('uid'))
//console.log(selectedObj);//(this.dataSource.data());
show_menu_details(selectedObj);
}
var statuses = [
{value:'', text:'--'},
{value:'Available', text:'Available'},
{value:'Locked', text:'Locked'},
{value:'Reserved', text:'Reserved'},
{value:'Occupied', text:'Occupied'}];
var floors = new Array();
floors[0]={text:'--',value:''};
_DS_Floor.fetch(function(data){
$.each(data.items,function(index,obj){
floors[index+1] = {text: obj.name, value: obj.id};
});
var grid = $("#list").kendoGrid({
dataSource: _DS_Room,
selectable: "row",
filterable: true,
columnMenu: true,
pageable: {refresh:true},
editable: {mode:"popup",confirmation:"Sure to delete?"},
height: 688,
scrollable: {
virtual: true
},
sortable: true,
toolbar: kendo.template($("#toolbar_template").html()),
columns: [//{field:'id',title:' ',width:40,template: '<input type="checkbox" id="#= id #" />'},
{field:'name',title:'Name'},
{field:'floor',title:'Floor',values:floors},
{field:'position',title:'Position'},
{field:'status',title:'Status',width:80,values:statuses}],//_Columns_Menu,//{ command: ['edit','destroy'], title: "", width: "200px" }
//change: onChange
});
grid.find("#btn-add").click(function(e){
e.preventDefault();
grid.data("kendoGrid").addRow();
});
grid.find("#btn-save").click(function(e){
e.preventDefault();
grid.data("kendoGrid").saveChanges();//editRow(grid.data("kendoGrid").select());
});
grid.find("#btn-remove").click(function(e){
e.preventDefault();
grid.data("kendoGrid").removeRow(grid.data("kendoGrid").select());
});
grid.find("#btn-cancel").click(function(e){
e.preventDefault();
grid.data("kendoGrid").cancelChanges();//removeRow(grid.data("kendoGrid").select());
});
});
});
</script>
Thanks.
Nullable values are not supported. Here is question from the KendoUI forums to which Vladimir Iliev provided explanation and solution. I hope this helps.

datepicker in mvc3 with razor engine

I have two datepicker in my view one for "From" and other for "to".
I want when "from" selected date less than "to" should disable.
and also please guide me how to format the view of datePicker
<div>
From:
<input type="text" id="txtFromDate" />
To:
<input type="text" id="txtToDate" />
</div>
$(function() {
$("#txtFromDate").datepicker({
numberOfMonths: 1,
highlightWeek: true,
onSelect: function(selected) {
$("#txtToDate").datepicker("option", "mindate", selected)
}
});
$("#txtToDate").datepicker({
numberOfMonths: 1,
onSelect: function(selected) {
$("#txtFromDate").datepicker("option", "maxDate", selected)
}
});
});
I got the solution...
$(function () {
$("#txtFromDate").datepicker({
changeMonth: true,
changeYear: true,
buttonImage: '../../Images/DatePicker.jpg',
dateFormat: 'dd-mm-yy',
buttonText: 'Select date:',
firstDay: 1,
buttonImageOnly: true,
showOn: 'both',
showAnim: 'fadeIn',
onSelect: function () {
var min = $(this).datepicker('getDate') || new Date(); // Selected date or today if none
var max = new Date(min.getTime());
max.setMonth(max.getMonth() + 12 * 10); // Add one month
$("#txtToDate").datepicker('option', { minDate: min, maxDate: max });
}
});
});
$(function () {
var min = $("#txtFromDate").datepicker('getDate')
$("#txtToDate").datepicker({
changeMonth: true,
changeYear: true,
buttonImage: '../../Images/DatePicker.jpg',
dateFormat: 'dd-mm-yy',
buttonText: 'Select date:',
firstDay: 1,
buttonImageOnly: true,
showOn: 'both',
showAnim: 'fadeIn',
onSelect: function () { $(this).trigger("onchange", null); }
});
});

Resources