dev
dev

Reputation: 121

Regards to textbox validation

I wrote a simple javascript function for validating textboxes in a aspx page

     <body>
     <script type="text/javascript" > 
      function checkTextbox(sender, target) {

      if (document.getElementById(sender).value  < document.getElementById(target).value) {
            var lbl = document.getElementById('<%=lbl_Outlet_Message.ClientID %>');
            lbl.style.display = 'block';
            lbl.value = "Enter Slab To Value should be greater or equals to From Value ";
        }

    }
</script>
<form id="form1" runat="server">
 <asp:Label ID="lbl_Outlet_Message" runat="server" ForeColor="Red" Visible="False"></asp:Label>
 <asp:TextBox ID="txt_from_02" runat="server" ></asp:TextBox> 
<asp:TextBox ID="txt_to_02" runat="server" onKeyUp="checkTextbox(this,'txt_from_02')">
</asp:TextBox>

</form>
</body>

When I am running aspx page, It is giving following error "0x800a01a8 - Microsoft JScript runtime error: Object required" I'm unable to know where I went wrong.

Upvotes: 2

Views: 122

Answers (3)

jomsk1e
jomsk1e

Reputation: 3625

document.getElementById can't find the ASP.NET control with just an ID name as a result document.getElementById(target) returns null and that throws an exception.

You should use clientID property.

Try changing this:

<asp:TextBox ID="txt_to_02" runat="server" onKeyUp="checkTextbox(this,'txt_from_02')">

To:

<asp:TextBox ID="txt_to_02" runat="server" onKeyUp="checkTextbox(this,'<%=txt_from_02.ClientId %>')">

Upvotes: 1

user3497034
user3497034

Reputation:

You are using document.getElementById function but you are not passing the Id of the textbox. So you are getting the error. You are passing the whole object of textbox by writing "this". So document.getElementById(sender) is not actually getting the id. Try with below solution and your code will work perfectly :

<body>
 <script type="text/javascript" > 
  function checkTextbox(sender, target) {

  if (document.getElementById(sender.id).value  < document.getElementById(target).value) {
        var lbl = document.getElementById('<%=lbl_Outlet_Message.ClientID %>');
        lbl.style.display = 'block';
        lbl.value = "Enter Slab To Value should be greater or equals to From Value ";
    }

}

Upvotes: 0

Adil
Adil

Reputation: 148110

The function checkTextbox expect the sender as id but you are passing the current object using this, you should use this.id instead of this or change the if condition by directly assessing value property of current object instead of pass the current object to document.getElementById

Change

if (document.getElementById(sender).value

To

if (sender.value

Upvotes: 1

Related Questions