JQuery DatePicker ReadOnly

后端 未结 14 2293
温柔的废话
温柔的废话 2020-12-03 04:35

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

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


        
14条回答
  •  眼角桃花
    2020-12-03 04:55

    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 = $('');
                $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);
            }
        });
    };
    

提交回复
热议问题