views:

6356

answers:

8

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 filll the textbox exclusively from the Datepicker calendar.

Is this possible?

JQuery 1.2.6
Datepicker 1.5.2

+12  A: 

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='readonly'>
Adam Bellaire
It worked! Thanks! However I had to use readonly="true" in the <input> element.
Elliot Vargas
A: 

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
+1  A: 

try

$("#my_txtbox").keypress(function(event) {event.preventDefault();});
Brad8118
I've used this with asp.net with success as it didn't play nice when setting the <asp:textbox> readonly attribute to "true"
Russ Cam
This does not prevent someone from pasting a value into the textbox for future reference.
Erik Philips
A: 

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
A: 

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

James Curran
A: 

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
+1  A: 
<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'

Chris
A: 

@Adhip: Thanks! Worked for me! :)

Chinmay