jQuery Date Picker where text input is read only

家住魔仙堡 提交于 2019-12-08 18:48:19

问题


I want to use the Jquery datepicker. I've got it setup using an the alt field option. I'm displaying D/M/Y in the text field, but submitting Y-M-D. Everything works fine so far, sending the correct data, etc.

However I want to stop the user from being able to manually type a date. I had originally set the INPUT field to disabled, which worked in every browser except IE. In IE it would popup the date picker but then not close after clicking a date.

Does anyone know the best way to do this?


回答1:


To prevent the user from manually editing the input, I would attach a keypress event and return false / prevent default from it's handler. This way if he has javascript he can use the datepicker, and if not he can manually edit the input.

$("#input-id").keypress(function (e)
{
    e.preventDefault();
});



回答2:


Extending nc3b's answer:

$("#input-id").keydown(function (e)
{e.preventDefault();});

will prevent keys such as backspace, delete, etc. Otherwise, you could have a date like 11/11/2012, and a user could backspace it to 11/11/201 and technically, thats still a valid date according to JS.




回答3:


You can also do this:

<input type="text" id="datepicker" name="datepicker" readonly="readonly" />

See the readonly attribute above.

If you also want the calendar to show when the <input> has focus, add this:

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



回答4:


After disabling the input field, use the destroy method to remove the datepicker. When re-enabling the field, just re-create the datepicker again.

$("#target").datepicker("destroy");


来源:https://stackoverflow.com/questions/2771137/jquery-date-picker-where-text-input-is-read-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!