JQuery DatePicker 只读

发布于 2024-12-10 14:53:06 字数 277 浏览 0 评论 0原文

当我将日期选择器设置为只读时,我发现用户无法在文本框中输入任何内容。

$("#datepicker").attr('readonly', 'readonly');

但是,他们仍然可以使用日历更改该值。如何隐藏日历以使用户无法更改日期值?

我不想禁用日期选择器,因为我需要在表单提交时将值发布到服务器。

("#datepicker").datepicker('disable');

When I make my datepicker read-only, I see that the user cannot type anything into the text box.

$("#datepicker").attr('readonly', 'readonly');

However, they can still change the value using the calendar. How can I hide the calendar so that users cannot change the date value?

I do not want to disable the datepicker since I need the value posted to the server upon form submit.

("#datepicker").datepicker('disable');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

时光磨忆 2024-12-17 14:53:06

我设置以下 beforeShow 事件处理程序(在选项参数中)来实现此功能。

beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }

I set the following beforeShow event handler (in the options parameter) to achieve this functionality.

beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }
烟织青萝梦 2024-12-17 14:53:06

您可以将允许的范围设置为某些无效范围,以便用户无法选择任何日期:

$("#datepicker").datepicker({minDate:-1,maxDate:-2}).attr('readonly','readonly');     

You can set the range allowed to some invalid range so the user can't select any date:

$("#datepicker").datepicker({minDate:-1,maxDate:-2}).attr('readonly','readonly');     
独孤求败 2024-12-17 14:53:06

如果您想重新启用日期选择器并保持其设置不变,所有列出的解决方案都会提供平庸的用户体验或导致问题。我使用了类似于将 select 设为只读的方法,即禁用它但添加一个同名的隐藏字段。检查一下:

用法:

$("#datepicker").readonlyDatepicker(true); //makes the datepicker readonly
$("#datepicker").readonlyDatepicker(false); //makes the datepicker editable again

jQuery 函数:

$.fn.readonlyDatepicker = function (makeReadonly) {
    $(this).each(function(){

        //find corresponding hidden field
        var name = $(this).attr('name');
        var $hidden = $('input[name="' + name + '"][type="hidden"]');

        //if it doesn't exist, create it
        if ($hidden.length === 0){
            $hidden = $('<input type="hidden" name="' + name + '"/>');
            $hidden.insertAfter($(this));
        }

        if (makeReadonly){
            $hidden.val($(this).val());
            $(this).unbind('change.readonly');
            $(this).attr('disabled', true);
        }
        else{
            $(this).bind('change.readonly', function(){
                $hidden.val($(this).val());
            });
            $(this).attr('disabled', false);
        }
    });
};

All of the listed solutions give a mediocre user experience or cause issues if you want to re-enable the datepicker with it's settings in-tact. I used a method similar to making a select read-only, which is to disable it but add a hidden field with the same name. Check it:

Usage:

$("#datepicker").readonlyDatepicker(true); //makes the datepicker readonly
$("#datepicker").readonlyDatepicker(false); //makes the datepicker editable again

jQuery function:

$.fn.readonlyDatepicker = function (makeReadonly) {
    $(this).each(function(){

        //find corresponding hidden field
        var name = $(this).attr('name');
        var $hidden = $('input[name="' + name + '"][type="hidden"]');

        //if it doesn't exist, create it
        if ($hidden.length === 0){
            $hidden = $('<input type="hidden" name="' + name + '"/>');
            $hidden.insertAfter($(this));
        }

        if (makeReadonly){
            $hidden.val($(this).val());
            $(this).unbind('change.readonly');
            $(this).attr('disabled', true);
        }
        else{
            $(this).bind('change.readonly', function(){
                $hidden.val($(this).val());
            });
            $(this).attr('disabled', false);
        }
    });
};
死开点丶别碍眼 2024-12-17 14:53:06

我的最终解决方案:

当我的应用程序加载时,我会这样初始化日期选择器:

$('.selector').datepicker({ dateFormat: "mm/dd/yy" }); 

然后我有一个全局切换按钮,可以启用/禁用日期选择器。要禁用我执行以下操作:

$('.selector').datepicker("option", "minDate", -1);
$('.selector').datepicker("option", "maxDate", -2); 

要启用我执行以下操作:

$('.selector').datepicker("option", "minDate", null);
$('.selector').datepicker("option", "maxDate", null); 

谢谢大家!

My final solution:

When my app loads I initialize the datepicker as such:

$('.selector').datepicker({ dateFormat: "mm/dd/yy" }); 

I then have a global toggle button that enables/disables the datepicker. To disable I do the following:

$('.selector').datepicker("option", "minDate", -1);
$('.selector').datepicker("option", "maxDate", -2); 

To enable I do the following:

$('.selector').datepicker("option", "minDate", null);
$('.selector').datepicker("option", "maxDate", null); 

Thanks everyone!

爱你不解释 2024-12-17 14:53:06

我用选择器解决了这个问题。我不会在只读输入上初始化日期时间选择器。

$('[type=datetime]:not([readonly])').datetimepicker();

I solved this with selector. I do not initialize the datetime picker on inputs which are readonly.

$('[type=datetime]:not([readonly])').datetimepicker();
温柔女人霸气范 2024-12-17 14:53:06

如果您尝试禁用该字段(但没有实际禁用它),请尝试将 onfocus 事件设置为 this.blur();。这样,每当字段获得焦点时,它就会自动失去焦点。

If you're trying to disable the field (without actually disabling it), try setting the onfocus event to this.blur();. This way, whenever the field gets focus, it automatically loses it.

染火枫林 2024-12-17 14:53:06

抱歉,Eduardos 解决方案对我不起作用。
最后,我意识到禁用的日期选择器只是一个只读文本框。
因此,您应该将其设置为只读并销毁日期选择器。
提交后字段将发送到服务器。

这是一些通用的代码,它采用多个文本框并使它们只读。
它也会删除日期选择器。

fields.attr("readonly", "readonly");
fields.each(function(idx, fld) {
    if($(fld).hasClass('hasDatepicker'))
    {
        $(fld).datepicker("destroy");
    }
});

Sorry, but Eduardos solution did not work for me.
At the end, I realized that disabled datepicker is just a read-only textbox.
So you should make it read only and destroy the datepicker.
Field will be sent to server upon submit.

Here is a bit generalized code that takes multiple textboxes and makes them read only.
It will strip off the datepickers as well.

fields.attr("readonly", "readonly");
fields.each(function(idx, fld) {
    if($(fld).hasClass('hasDatepicker'))
    {
        $(fld).datepicker("destroy");
    }
});
久光 2024-12-17 14:53:06

按键=>防止违约...

onkeypress = > preventdefault ...

梦境 2024-12-17 14:53:06

我提出了另一个与提议的解决方案不同的解决方案。使用日期选择器时,它会创建一个类似于弹出窗口的 div,单击输入字段时会定位该弹出窗口。要删除它,我只需设置 CSS 的可见性属性,使其不显示。

if ($('.yourDatepickerSelector').prop('readonly')) {
    $('#ui-datepicker-div').css({ 'visibility': 'hidden' })
} else { $('#ui-datepicker-div').css({ 'visibility': 'visible' }) }

这似乎也正确地发布到服务器,并且不应该影响与其关联的任何设置。

I came up with another solution that is different than what had been proposed. When the date picker is used, it creates a div similar to a pop-up that is positioned when the input field is clicked on. To remove it, I just set the visibility property of the CSS so that it doesn't show up.

if ($('.yourDatepickerSelector').prop('readonly')) {
    $('#ui-datepicker-div').css({ 'visibility': 'hidden' })
} else { $('#ui-datepicker-div').css({ 'visibility': 'visible' }) }

This also seems to post correctly to the server, and should not effect any of the settings associated with it.

浅笑依然 2024-12-17 14:53:06
<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

对我有用。

<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

Works for me.

溺渁∝ 2024-12-17 14:53:06
      beforeShow: function(el) {
            if ( el.getAttribute("readonly") !== null ) {
                if ( (el.value == null) || (el.value == '') ) {
                    $(el).datepicker( "option", "minDate", +1 );
                    $(el).datepicker( "option", "maxDate", -1 );
                } else {
                    $(el).datepicker( "option", "minDate", el.value );
                    $(el).datepicker( "option", "maxDate", el.value );
                }
            }
        },
      beforeShow: function(el) {
            if ( el.getAttribute("readonly") !== null ) {
                if ( (el.value == null) || (el.value == '') ) {
                    $(el).datepicker( "option", "minDate", +1 );
                    $(el).datepicker( "option", "maxDate", -1 );
                } else {
                    $(el).datepicker( "option", "minDate", el.value );
                    $(el).datepicker( "option", "maxDate", el.value );
                }
            }
        },
陌路黄昏 2024-12-17 14:53:06

通过禁用日期选择器输入来实现这一点,但如果您想提交表单数据,那么它是一个问题。

所以经过大量的调整,这对我来说似乎是一个完美的解决方案

1.在某些条件下使您的 HTML 输入只读。

<input class="form-control date-picker" size="16" data-date-format="dd/mm/yyyy"
                       th:autocomplete="off"
                       th:name="birthDate" th:id="birthDate"
                       type="text" placeholder="dd/mm/jjjj"
                       th:value="*{#dates.format(birthDate,'dd/MM/yyyy')}"
                       th:readonly="${client?.isDisableForAoicStatus()}"/>

2.在你的js的ready函数中检查readonly属性。

 $(document).ready(function (e) {

            if( $(".date-picker").attr('readonly') == 'readonly') {
                $("#birthDate").removeClass('date-picker');
            }
     });

当您单击只读字段时,这将停止调用日历弹出窗口。而且这不会在提交数据时产生任何问题。但是,如果您禁用该字段,则将不允许您提交值。

by making date picker input disabled achieve this but if you want to submit form data then its a problem.

so after lot of juggling this seems to me a perfect solution

1.make your HTML input readonly on some condition.

<input class="form-control date-picker" size="16" data-date-format="dd/mm/yyyy"
                       th:autocomplete="off"
                       th:name="birthDate" th:id="birthDate"
                       type="text" placeholder="dd/mm/jjjj"
                       th:value="*{#dates.format(birthDate,'dd/MM/yyyy')}"
                       th:readonly="${client?.isDisableForAoicStatus()}"/>

2. in your js in ready function check for readonly attribute.

 $(document).ready(function (e) {

            if( $(".date-picker").attr('readonly') == 'readonly') {
                $("#birthDate").removeClass('date-picker');
            }
     });

this will stop the calendar pop up invoking when you click on the readonly field.also this will not make any problem in submit data. But if you make the field disable this will not allow you to submit value.

爱的故事 2024-12-17 14:53:06

在初始化期间,您必须将选项 enableOnReadonly 设置为 false,默认情况下为 true。

$('#datepicker').datepicker({
    enableOnReadonly: false
});

然后,您需要将该字段设置为只读

$('#datepicker').prop('readonly', true);

请参阅 https://bootstrap- datepicker.readthedocs.io/en/latest/options.html#enableonreadonly

During initialization you have to set to false the option enableOnReadonly which by default is true.

$('#datepicker').datepicker({
    enableOnReadonly: false
});

Then, you need to make the field readonly

$('#datepicker').prop('readonly', true);

See https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#enableonreadonly

偏爱自由 2024-12-17 14:53:06

这对我有用

document.getElementById("datepicker").disabled = true; //makes the datepicker readonly

document.getElementById("datepicker").disabled = false; //makes the datepicker enabled

This Worked For Me

document.getElementById("datepicker").disabled = true; //makes the datepicker readonly

document.getElementById("datepicker").disabled = false; //makes the datepicker enabled
蓝眼睛不忧郁 2024-12-17 14:53:06
Readonly datepicker with example (jquery) - 
In following example you can not open calendar popup.
Check following code see normal and readonly datepicker.

Html Code- 

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Datepicker functionality</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <!-- Javascript -->
      <script>
         $(function() {
                var currentDate=new Date();
                $( "#datepicker-12" ).datepicker({
                  setDate:currentDate,
                  beforeShow: function(i) { 
                      if ($(i).attr('readonly')) { return false; } 
                   }
                });
                $( "#datepicker-12" ).datepicker("setDate", currentDate);
                $("#datepicker-13").datepicker();
                $( "#datepicker-13" ).datepicker("setDate", currentDate);
        });
      </script>
   </head>

   <body>
      <!-- HTML --> 
      <p>Readonly DatePicker: <input type = "text" id = "datepicker-12" readonly="readonly"></p>
      <p>Normal DatePicker: <input type = "text" id = "datepicker-13"></p>
   </body>
</html>

Readonly datepicker with example (jquery) - 
In following example you can not open calendar popup.
Check following code see normal and readonly datepicker.

Html Code- 

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Datepicker functionality</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <!-- Javascript -->
      <script>
         $(function() {
                var currentDate=new Date();
                $( "#datepicker-12" ).datepicker({
                  setDate:currentDate,
                  beforeShow: function(i) { 
                      if ($(i).attr('readonly')) { return false; } 
                   }
                });
                $( "#datepicker-12" ).datepicker("setDate", currentDate);
                $("#datepicker-13").datepicker();
                $( "#datepicker-13" ).datepicker("setDate", currentDate);
        });
      </script>
   </head>

   <body>
      <!-- HTML --> 
      <p>Readonly DatePicker: <input type = "text" id = "datepicker-12" readonly="readonly"></p>
      <p>Normal DatePicker: <input type = "text" id = "datepicker-13"></p>
   </body>
</html>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文