Monday, 14 August 2017

Trigger DatePicker Onchange Event in CRM Portal

In CRM portal the onchange event is will be working usual jQuery method for text field but when it comes to date fields we cant call the onchange event using the Date field id rather we can call this using Div Control.

I got a requirement that when user select future date, should alert that "future date is not allowed".

for example if user select the future date for "Date Of Birth" field it should alert the user to select past date.

Step 1:

Step 2: Open Developer tool (Press F12) and select console tab

Step 3: Type $('div.control')

Step 4: Inspect the field and get the div control index.

Step 5: In this example my field is in index 8.


Step 6: Copy the below code and paste in your custom js placeholder using inline editing tool for your page.

Sample Code:

var dp123 = $('div.control')[8];
$(dp123).on("dp.change",function(e){
    alert("The onchange event of datepicker is fired");
    var today = new Date();
    if(e.date > today)
    {
    alert("Future Date is not allowed");
     }
  });


8 comments:

  1. Hi Syed,

    Thanks for sharing. Unable to find the div control index. Getting default.preform.bundle.js:7 Deprecation warning in console.

    Thanks & Regards,
    Nandhini M

    ReplyDelete
  2. Hi Nandhini,

    Just type $('div.control') in console it will list all the div controls with index. If you mouse over the list it will point to that particular field. You can get the index of the particular field from the list.

    Thanks
    Syed

    ReplyDelete
  3. Deprecation warning will not cause any issue. Ignore it.

    ReplyDelete
  4. Maybe better way use next code
    $("#").parent("div.control").on("dp.change",function(e){
    // do something
    });
    I think that this code is more dynamic

    ReplyDelete
  5. Sorry. When I inserted code some part was lost
    $("#yourDatetimeField").parent...

    ReplyDelete
    Replies
    1. hi Sergey,

      Sry for the delayed response. Triggering onchange of the field is not an issue, setting new value was not working. We have to use the below code for this

      To restrict DOB as feature date:

      if($("#birthdate").val()!='' ||$("#birthdate").val() !=null){
      var DOB = new Date($("#birthdate").val())
      if (DOB.isAfter(new Date())){
      $("#DateFormatValidatorbirthdate").html("Birthdate cannot be future date");
      $("#DateFormatValidatorbirthdate").css('visibility', 'visible');
      return false;
      }

      Delete
  6. Hi Could you please help with below minor issue

    Using entity form and reading value of 2 optionset value $('#optionset').val() but it always gives null value for 2 option set field .

    ReplyDelete
  7. Hi Syed,
    only one issue with Datepicker is when we select the same date the event is not triggering.
    For example, if you select 16th and then selects the same date then the on change event is not triggering.
    Thanks
    CG

    ReplyDelete