2017-08-31 22 views
0

我在JavaScript中爲我的文本框在aspx頁面中創建自動選項卡功能。當我試圖專注於下一個文本框時,我收到一條錯誤消息 "Unable to get property 'focus' of undefined or null reference"文本框在javascript中爲空或未定義

<asp:TextBox type="text" ID="areaCodeTextBox" runat="server" MaxLength="3" size="1" onkeypress="return isNumberKey(event)" onkeyup="Tab(this, 'exchangeTextBox')" /> 
    <asp:TextBox type="text" ID="exchangeTextBox" runat="server" MaxLength="3" size="1" onkeypress="return isNumberKey(event)" onkeyup="Tab(this, 'suffixTextBox')"/> 
    <asp:TextBox type="text" ID="suffixTextBox" runat="server" MaxLength="4" size="2" onkeypress="return isNumberKey(event)" /> 

    <SCRIPT language=Javascript> 
    function isNumberKey(evt) 
    { 
    var charCode = (evt.which) ? evt.which : evt.keyCode; 
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
     return false;  
    return true; 
    } 
    function Tab(fromTextBox, toTextBox) { 
     // Determine if the current field's max length has been reached. 
     var length = fromTextBox.value.length; 
     var maxLength = fromTextBox.getAttribute("maxLength"); 
     if (length == maxLength) { 
      // Retreive the next field in the tab sequence, and give it the focus. 

      document.getElementById(toTextBox).focus(); 
     } 
    } 
</SCRIPT> 

有什麼明顯的,我做錯了我調用焦點方法的方式嗎?

編輯*我沒有直接在JavaScript中引用文本框,我試圖將ID作爲參數傳遞。這會對文本框爲什麼會返回爲空作出改變嗎?

+3

可能的複製[的document.getElementById ('id').aspx失敗的ASP.net javascript函數](https://stackoverflow.com/questions/9101904/document-getelementbyidid-value-failing-in-asp-net-javascript-function) –

回答

0

我還沒有100%地肯定爲什麼上面沒有工作,但是這是我的修復

<script> 
// A $(document).ready() block. 
$(document).ready(function() { 
    //Attach key up event handler 
    $('#<%= areaCodeTextBox.ClientID %>').keyup(function() { 
       //check if user typed three characters 
       if (this.value.length == $(this).attr('maxlength')) { 
        //move the focus to another textbox 
        $('#<%= exchangeTextBox.ClientID %>').focus(); 
       } 
      }); 
      $('#<%= exchangeTextBox.ClientID %>').keyup(function() { 
       if (this.value.length == $(this).attr('maxlength')) { 
        $('#<%= suffixTextBox.ClientID %>').focus(); 
       } 
      }); 
     }); 
</script> 

我拿出參數和由它製成的靜態