2012-01-24 30 views
3

我注意到這裏有幾個帖子禁止免費鍵入到JQuery DatePicker文本框中,例如 禁用DatePicker文本框中的自由文本 - 但允許刪除

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

<input type="text" name="date" readonly="readonly" /> 

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

但是沒有人允許您刪除已經填充文本框的任何日期。有沒有人知道這樣做的方式?我還需要在回發時保持價值。

非常感謝

回答

0

我想出的最好的解決方案就是自己做。這需要很多步驟。首先,你需要禁止除退格鍵(也可能是刪除鍵)以外的所有鍵作爲你的日期選擇器文本輸入。我用下面的代碼做了這個。

$(document).keydown(function(e){ 
    var elid = $(document.activeElement).is('#yourDatepicker'); 
    if(e.keyCode === 8 && elid){ 
     return true; //allow the backspace character 
    } 
    else { 
     return false; //disallow all other characters 
    } 
}); 

這很好,但後來我發現用戶只能刪除一些日期而不是全部日期。我不喜歡這個,所以我決定選擇文字。我必須考慮文本焦點和點擊時已經在焦點。

我這樣做是用下面的代碼:

//When you click the text box, select all text. 
$('#yourDatepicker').focus(function() { 
    var $this = $(this); 

    $this.select(); 

    window.setTimeout(function() { 
     $this.select(); 
    }, 1); 

    // Workaround for chrome 
    function mouseUpHandler() { 
     $this.off("mouseup", mouseUpHandler); 
     return false; 
    } 

    $this.mouseup(mouseUpHandler); 

    //When in focus, make it so the text is still selected after a click. 
    $this.click(function() { 
     window.setTimeout(function() { 
      $this.select(); 
     }, 1); 

     // Workaround for chrome 
     function mouseUpHandler() { 
      $this.off("mouseup", mouseUpHandler); 
      return false; 
     } 
    }); 
}); 

有時你也需要看看剩下的焦點一個文本框的情況下,日期已更改後。我決定將焦點從文本框中移除,但是您也可以執行與上面類似的選擇功能。爲了消除焦點,你實際上使用日期選擇器的「onSelect」。

例如:

//A date change has occurred 
$('#yourDatepicker').datepicker({ 
    stuff: 'stuff', 
    morestuff: 'moreStuff', 
    onSelect: function() { 
     $(this).blur(); //This takes the focus off of the textbox 
    } 
}); 

就像之前說的,你可以替換用於焦點的一個功能/點擊情況。最後,你需要考慮試圖粘貼到文本框中的用戶。這裏是我的代碼:

//NO PASTES ALLOWED!!!!! 
$('#yourDatepicker').bind('paste', function(e) { 
    e.preventDefault(); 
});