0

I am creating an auto tab function in JavaScript for my textboxes in an aspx page. When I try to focus on the next textbox I get an error message "Unable to get property 'focus' of undefined or null reference" .

   <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>

Is there something obvious that I am doing wrong with the way I am calling the focus method?

Edit* I am not referencing the textboxes directly in the javascript, I am trying to pass the ID in as a parameter. Would that make a difference as to why the textbox is coming back as null?

  • 3
    Possible duplicate of [document.getElementById('id').value failing in ASP.net javascript function](https://stackoverflow.com/questions/9101904/document-getelementbyidid-value-failing-in-asp-net-javascript-function) – James Thorpe Aug 31 '17 at 16:53

1 Answers1

0

I'm still not 100% sure why the above didn't work but this was my fix

<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>

I took out the parameters and made it static