147

How do I use the jQuery Datepicker with a textbox input:

$("#my_txtbox").datepicker({
  // options
});

that doesn't allow the user to input random text in the textbox. I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar.

Is this possible?

jQuery 1.2.6
Datepicker 1.5.2

informatik01
  • 16,038
  • 10
  • 74
  • 104
Elliot Vargas
  • 20,499
  • 11
  • 34
  • 36

25 Answers25

283

You should be able to use the readonly attribute on the text input, and jQuery will still be able to edit its contents.

<input type='text' id='foo' readonly='true'>
koenHuybrechts
  • 868
  • 4
  • 15
  • 28
Adam Bellaire
  • 108,003
  • 19
  • 148
  • 163
  • 30
    For People that have Javascript disabled I would leave the input field alone in the HTML and have the bit of jQuery place the readonly attribute on the page load $(document).ready(function () { $("#my_txtbox").attr 'readOnly' , 'true' ); }); That way users with JS turned off can still pick a date – SimonGates Mar 29 '11 at 11:49
  • 6
    this is great.. however the default styling that Chrome (and possibly other browsers) adds to readonly attributes is really unpleasant, so be sure you override it – Damon Jun 07 '12 at 19:35
  • Attention. With `readonly` datepicker the final user **will be able to manpilate** the field value by picking another date from the datepicker, as in this bug: http://bugs.jqueryui.com/ticket/13107 – serge Jun 11 '15 at 15:07
  • 1
    @FooBar You proposed a practical solution; just a note that the current preferred way (as some time has passed since your comment) to setting the readonly attribute is via the prop() method: `$("#my_txtbox").prop('readonly', true)` – Werner Jun 12 '15 at 09:32
  • 1
    @Werner thanks for the tip..... It's funny because 4 years later.... I am no longer worried about people with JavaScript disabled :) – SimonGates Jun 16 '15 at 15:04
  • 2
    As per WC3 HTML specification, its only or without true/false https://www.w3.org/TR/html5/forms.html#the-readonly-attribute – Ankit Sharma Sep 21 '16 at 14:13
  • 5
    I'd use a cursor pointer to make it look clickable `` – Benjamin Lucidarme May 19 '17 at 11:46
62

Based on my experience I would recommend the solution suggested by Adhip Gupta:

$("#my_txtbox").attr( 'readOnly' , 'true' );

The following code won't let the user type new characters, but will allow them to delete characters:

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

Additionally, this will render the form useless to those who have JavaScript disabled:

<input type="text" readonly="true" />
Jonathan Bender
  • 1,911
  • 4
  • 22
  • 39
2046
  • 621
  • 5
  • 2
  • 3
    OP should consider marking this as the answer due to the JavaScript disable scenario. – CeejeeB Sep 21 '12 at 14:24
  • 7
    in what parallel universe people use regular web site with disabled javascript ? – d.raev Dec 11 '13 at 08:04
  • How would this JAVASCRIPT answer help if JavaScript was disabled anyway? – PW Kad Nov 05 '14 at 22:45
  • 1
    @PWKad by adding the `readonly` attribute to the field via JS, you ensure that if they have JavaScript disabled (and therefore won't be able to use the datepicker), they can still use the form via standard manual entry. – Jonathan Bender Nov 17 '14 at 21:35
  • 2
    At the time of writing, this is the preferred way to set the readonly attribute using jQuery: `$("#my_txtbox").prop('readonly', true)`; – Werner Jun 12 '15 at 09:29
13

try

$("#my_txtbox").keypress(function(event) {event.preventDefault();});
Brad8118
  • 4,672
  • 11
  • 36
  • 48
10

If you are reusing the date-picker at multiple places then it would be apt to modify the textbox also via JavaScript by using something like:

$("#my_txtbox").attr( 'readOnly' , 'true' );

right after/before the place where you initialize your datepicker.

Adhip Gupta
  • 7,063
  • 7
  • 34
  • 46
6
<input type="text" readonly="true" />

causes the textbox to lose its value after postback.

You rather should use Brad8118's suggestion which is working perfectly.

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

EDIT: to get it working for IE use 'keydown' instead of 'keypress'

6

After initialising the date picker:

$(".project-date").datepicker({
    dateFormat: 'd M yy'
});

$(".project-date").keydown(false);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
umutesen
  • 2,523
  • 1
  • 27
  • 41
4

You have two options to get this done. (As far as i know)

  1. Option A: Make your text field read only. It can be done as follows.

  2. Option B: Change the curser onfocus. Set ti to blur. it can be done by setting up the attribute onfocus="this.blur()" to your date picker text field.

Ex: <input type="text" name="currentDate" id="currentDate" onfocus="this.blur()" readonly/>

steveb
  • 5,382
  • 2
  • 27
  • 36
user2182143
  • 992
  • 9
  • 10
  • 2
    the blur hack was kinda awesome. The field didn't have to be readonly which confuses some users when they get the giant red STOP on a field in Chrome... it prevents cut and paste, deletions, typing, etc... and the jquery datepicker still works just fine... – David C Jun 17 '15 at 15:06
4
$("#txtfromdate").datepicker({         
    numberOfMonths: 2,
    maxDate: 0,               
    dateFormat: 'dd-M-yy'       
}).attr('readonly', 'readonly');

add the readonly attribute in the jquery.

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
Chenthil
  • 296
  • 4
  • 9
3

To datepicker to popup on gain focus:

$(".selector").datepicker({ showOn: 'both' })

If you don't want user input, add this to the input field

<input type="text" name="date" readonly="readonly" />
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
3

I just came across this so I am sharing here. Here is the option

https://eonasdan.github.io/bootstrap-datetimepicker/Options/#ignorereadonly

Here is the code.

HTML

<br/>
<!-- padding for jsfiddle -->
<div class="input-group date" id="arrival_date_div">
  <input type="text" class="form-control" id="arrival_date" name="arrival_date" required readonly="readonly" />
  <span class="input-group-addon">
    <span class="glyphicon-calendar glyphicon"></span>
  </span>
</div>

JS

$('#arrival_date_div').datetimepicker({
  format: "YYYY-MM-DD",
  ignoreReadonly: true
});

Here is the fiddle:

http://jsfiddle.net/matbaric/wh1cb6cy/

My version of bootstrap-datetimepicker.js is 4.17.45

Matija
  • 17,604
  • 2
  • 48
  • 43
2

I know this thread is old, but for others who encounter the same problem, that implement @Brad8118 solution (which i prefer, because if you choose to make the input readonly then the user will not be able to delete the date value inserted from datepicker if he chooses) and also need to prevent the user from pasting a value (as @ErikPhilips suggested to be needed), I let this addition here, which worked for me: $("#my_txtbox").bind('paste',function(e) { e.preventDefault(); //disable paste }); from here https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript and the whole specific script used by me (using fengyuanchen/datepicker plugin instead):

$('[data-toggle="datepicker"]').datepicker({
    autoHide: true,
    pick: function (e) {
        e.preventDefault();
        $(this).val($(this).datepicker('getDate', true));
    }
}).keypress(function(event) {
    event.preventDefault(); // prevent keyboard writing but allowing value deletion
}).bind('paste',function(e) {
    e.preventDefault()
}); //disable paste;
2

Instead of adding readonly you can also use onkeypress="return false;"

Krishnan KK
  • 313
  • 4
  • 13
1

This demo sort of does that by putting the calendar over the text field so you can't type in it. You can also set the input field to read only in the HTML to be sure.

<input type="text" readonly="true" />
Zach
  • 24,496
  • 9
  • 43
  • 50
1

HTML

<input class="date-input" type="text" readonly="readonly" />

CSS

.date-input {
      background-color: white;
      cursor: pointer;
}
kayz1
  • 7,260
  • 3
  • 53
  • 56
0

I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.

James Curran
  • 101,701
  • 37
  • 181
  • 258
0
$('.date').each(function (e) {
    if ($(this).attr('disabled') != 'disabled') {
        $(this).attr('readOnly', 'true');
        $(this).css('cursor', 'pointer');
        $(this).css('color', '#5f5f5f');
    }
});
LithiumD
  • 21
  • 2
0

Here is your answer which is way to solve.You do not want to use jquery when you restricted the user input in textbox control.

<input type="text" id="my_txtbox" readonly />  <!--HTML5-->

<input type="text" id="my_txtbox" readonly="true"/>
kleopatra
  • 51,061
  • 28
  • 99
  • 211
johnkhadka
  • 41
  • 7
0

$("#my_txtbox").prop('readonly', true)

worked like a charm..

0

Instead of using textbox you can use button also. Works best for me, where I don't want users to write date manually.

enter image description here

Ajjay Arora
  • 144
  • 2
  • 4
  • 10
0

I know this question is already answered, and most suggested to use readonly attribure.
I just want to share my scenario and answer.

After adding readonly attribute to my HTML Element, I faced issue that I am not able to make this attribute as required dynamically.
Even tried setting as both readonly and required at HTML creation time.

So I will suggest do not use readonly if you want to set it as required also.

Instead use

$("#my_txtbox").datepicker({
    // options
});

$("#my_txtbox").keypress(function(event) {
    return ( ( event.keyCode || event.which ) === 9 ? true : false );
});

This allow to press tab key only.
You can add more keycodes which you want to bypass.

I below code since I have added both readonly and required it still submits the form.
After removing readonly it works properly.

https://jsfiddle.net/shantaram/hd9o7eor/

$(function() {
  $('#id-checkbox').change( function(){
   $('#id-input3').prop('required', $(this).is(':checked'));
  });
  $('#id-input3').datepicker();
  $("#id-input3").keypress(function(event) {
    return ( ( event.keyCode || event.which ) === 9 ? true : false );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet"/>

<form action='https://jsfiddle.net/'>
Name:  <input type="text" name='xyz' id='id-input3' readonly='true' required='true'> 
    <input type='checkbox' id='id-checkbox'> Required <br>
    <br>
    <input type='submit' value='Submit'>
</form>
Shantaram Tupe
  • 1,646
  • 3
  • 16
  • 42
0

replace the ID of time picker: IDofDatetimePicker to your id.

This will prevent the user from entering any further keyboard inputs but still, the user will be able to access the time popup.

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

Try this source: https://github.com/jonthornton/jquery-timepicker/issues/109

Mohan
  • 43
  • 5
0

This question has a lot of older answers and readonly seems to be the generally accepted solution. I believe the better approach in modern browsers is to use the inputmode="none" in the HTML input tag:

<input type="text" ... inputmode="none" />

or, if you prefer to do it in script:

$(selector).attr('inputmode', 'none');

I haven't tested it extensively, but it is working well on the Android setups I have used it with.

Peter Bowers
  • 3,063
  • 1
  • 10
  • 18
0

In my case i have use disableTextInput property

$( ".datepicker" ).datepicker({'dateFormat' : 'd-m-y', 'disableTextInput':true });
Ahmed Awan
  • 347
  • 3
  • 9
-1

Or you could, for example, use a hidden field to store the value...

        <asp:HiddenField ID="hfDay" runat="server" />

and in the $("#my_txtbox").datepicker({ options:

        onSelect: function (dateText, inst) {
            $("#<% =hfDay.ClientID %>").val(dateText);
        }
Steinwolfe
  • 81
  • 1
  • 4
-1

If you want the user to select a date from the datepicker but you dont want the user to type inside the textbox then use the following code :

<script type="text/javascript">
$(function () {
    $("#datepicker").datepicker({ maxDate: "-1D" }).attr('readonly', 'readonly');
    $("#datepicker").readonlyDatepicker(true);

});