2011-12-06 28 views
0

只有在輸入字段的文本不符合一組條件時,我才需要啓動.datepicker。但是,我不知道如何啓動.datepicker,而不是直接從獲取焦點或正在按下按鈕的字段中啓動。從另一個JS函數啓動jQuery .datepicker

我試圖做...

的HTML

<input type="text" id="userDate" name="userDate" style="width: 100px;" onblur="checkDate(this.id);" /> 

的JS

function checkDate(theId) 
{ 
    var enteredValue = document.getElementById(theId).value; 
    var checkedValue = evaluateValue(enteredValue); // this checks to see if the text meets the criteria 

    if (checkedValue == null) 
    { 
     // this is where I want to call the .datepicker to have the calendar show up 
     $("#userDate").datepicker(); 
    } 
    else 
    { 
     document.getElementById(theId).value = checkedValue; 
    } 
} 

我知道,這將是更容易,如果日曆剛上來的時候文本字段變得焦點。但是,這不是客戶希望它工作的方式。只要符合所需的格式,他們就會接受用戶輸入。如果沒有,那麼他們想要日曆和默認的強制格式。

謝謝。

+0

我建議在jquery中綁定onblur事件。而不是在HTML中。 – albertjan

回答

3

如果您使用的是jQuery用戶界面的日期選擇器,你會表現出這樣的日期選擇器:

$("#userDate").datepicker("show"); 

編輯:

你的代碼很可能將不得不是這個樣子:

$(function(){ 
    $("#userDate").datepicker(); // <-- Create the datepicker on load 
}); 

function checkDate(theId) 
{ 
    var enteredValue = document.getElementById(theId).value; 
    var checkedValue = evaluateValue(enteredValue); // this checks to see if the text meets the criteria 

    if (checkedValue == null) 
    { 
     // this is where I want to call the .datepicker to have the calendar show up 
     $("#userDate").datepicker("show"); // <-- Show datepicker when needed 
    } 
    else 
    { 
     document.getElementById(theId).value = checkedValue; 
    } 
} 
+0

當我使用上面的代碼時,我在錯誤控制檯中收到一條消息,指出「a未定義在(http://ajax.googleapis.com/...)」 – seveninstl

+0

@ user1084262請參閱我的更新答案,需要在加載時創建日期選擇器。 –

+0

我已經試過了。問題是當文本字段首先獲得焦點時,日曆彈出。我需要一種方法來壓制這一點。我也嘗試將datepicker初始化爲禁用,但也禁用了輸入字段,而不僅僅是彈出式日曆。 – seveninstl

0

好吧,經過很多百事可樂百事可樂和更多小時的研究,試驗和錯誤;這是我想出來的...並且它符合我的需求。

$(document).ready(function() 
    { 
     $("#userDate").blur(function() 
     { 
      var convertResults = convertMyDate('userDate'); // call to my code that checks the date for accepted formats 

      if (convertResults == null) 
      { 
       $("#userDate").datepicker({ 
        changeMonth: true, 
        changeYear: true 
       }); 
       $("#userDate").datepicker("show"); 
      } 
      else 
      { 
       document.getElementById('userDate').value = convertResults.toString('MM/dd/yyyy'); 
      } 
     }); 
    }); 

現在唯一的問題是客戶端的窗體有14個日期字段。所以...在我的代碼中多複製13次!?我現在只是沒有時間想出一種方法將所有這些都轉化爲一個功能,它將在循環中啓動所有這些功能...

任何建議,將不勝感激。

相關問題