Monday, 12 August 2013

JavaScript for DateTime Picker - SharePoint

Hi All,
 In my previous post, i shared about the "onchange" event.
If u had tried this on "DateTime" field, u would have faced the difficulty.
I faced the same and it took time for me to sort this out:P

Ok, i will tell u the tweak to make that working.

In a Datetime picker there are two ways of changing the date.
Condition 1) Picking from the Image which is on the right side of the control.
Condition 2) Directly changing the date in the Textbox.

"onchange" works for the condition 2).

But condition 1) is mostly preferred by the users.

For this situation we have to use "onvaluesetfrompicker" event. I will show you one sample code.

There is one Datetime picker field - "Publishing date". This field should not be less than today. If it is less then, an alert has to come and "Save" button should be hided.

========================================================================

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$(document).ready(function()
{
 today = new Date();

getTagFromIdentifierAndTitle("input","DateTimeFieldDate","Publishing Date").onvaluesetfrompicker = function() {ChangeEvent1()}; //This checks condition 2
getTagFromIdentifierAndTitle("input","DateTimeFieldDate","Publishing Date").onchange = function() {ChangeEvent1()};  //This checks condition 1

});


function ChangeEvent1()
{

var dateSelected = document.getElementById("ctl00_m_g_5cee28ab_e950_4028_95bc_0cb0d55ec872_ctl00_ctl05_ctl09_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDate");
var pubdate = new Date(dateSelected.value);

if(pubdate<=today)
{
$("input[value$='Save']").attr('disabled', true); //button hides
alert("Publishing Date should be greater than Today's Date");
}

else
{
$("input[value$='Save']").attr('disabled', false); //button shown
}
}

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
 var len = identifier.length;
 var tags = document.getElementsByTagName(tagName);
 for (var i=0; i < tags.length; i++) {
 var tempString = tags[i].id;
 if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
 return tags[i];
 }
 }
 return null;
}

</script>
========================================================================

Have a great day :)
See u all on the Next post :D

1 comment: