Making Kendo Datepicker readonly but also selectable

gardarvalur picture gardarvalur · Aug 19, 2013 · Viewed 8.2k times · Source

I´ve been struggling to make my Kendo Datepicker without user-text-input and the only solution I´ve come up with was making the tag "readonly". However I want to be able to select the date from the selector with the mouse without being able to input text directly to the picker, therefore making the datepicker readonly but selectable.

Any ideas how?

                <div>
                    @(Html.Kendo().DatePicker()
                          .Start(CalendarView.Year)
                          .Name("DatePicker")
                          .Value(DateTime.Now.AddDays(-365))
                          .Max(DateTime.Now)
                          .HtmlAttributes(new { style = "width: 125px;"  })
                          .Events(e => e.Change("onDateChange")))
                </div>

Answer

gardarvalur picture gardarvalur · Aug 19, 2013

After a while I found a very simple solution using javascript. I simply declared a script that prevents any user input without disabling or making the input readonly. Something like this:

$("#inputId").keypress(function (evt) {
    var keycode = evt.charCode || evt.keyCode;
    if (keycode == 9) { //allow Tab through
        return true;
    } else {
        return false;
    }
});

It was easier than I thought :)

########### EDITED ####################

As suggested in a comment, it is probably not good practice to suppress all the keystrokes so I will paste almost the same code but suggesting that I open the datePicker instead (but still kind of suppressing the user text input as well).

$("#inputId").keypress(function (evt) {
    var keycode = evt.charCode || evt.keyCode;
    if (keycode == 9) { //allow Tab through
        return true;
    } else {
        // Allow the datepicker to open instead
        var datePicker = $("#inputId").data("kendoDatePicker");
        datePicker.open();
        return false;
    }
});