MNie
MNie

Reputation: 1367

How to call JS function in asp.net

My problem is that i want to call a js function on a TextBox attribute "OnTextChanged", the js function should check if the text in TextBox is correct and set visibility of Button.

Here is my asp code:

...
<head runat="server">
...
<script type="text/javascript" src="<%# Page.ResolveClientUrl("Verify.js") %>"></script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="FirstTextBox" ClientIDMode="Static" runat="server" ></asp:TextBox>
        <asp:Button ID="AddButton" runat="server" Text="Add person" Height="23px" OnClick="AddButton_Click"/>
...
</form>
</body>

js(in another file):

function Valid()
{
    var textBox = '<%= FirstTextBox.ClientID %>';
    var acceptButton = '<%= AddButton.ClientID %>';
    var text= document.getElementById(textBox).value;
    var accept = document.getElementById(acceptButton);
    if(data correct)
    {
        do things..
    }
    else
    {
        accept.style.display = 'none';
    }
}

and in c# code i set attribute for TextBox.

ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("Verify", "Verify.js");
this.FirstTextBox.Attributes.Add("OnTextChanged", "Valid()");

JS function isn't execute, it looks like the program even didn't go inside the js funcion. Anyone have an idea what i doing wrong? Thanks for help!

Upvotes: 1

Views: 196

Answers (2)

paramosh
paramosh

Reputation: 2258

You should use onchange instead of OnTextChanged which is Server Side event.

Upvotes: 1

user61470
user61470

Reputation:

I think there are two issues here:

  1. There isn't a javascript event OnTextChanged this should be updated to onchange or onkeypress depending on the responsiveness you are looking for.
  2. Your external javascript value contains code blocks which will not be evaluated, as powerful as .NET can be it's not going to randomly parse your resources for code blocks and attempt to make sense of them in the current context.

Given your current set up I think the easiest way is to update your code as follows:

JS:

function Valid(textboxId, btnId){
    var textBox = textboxId;
    var acceptButton = btnId;
    var text= document.getElementById(textBox).value;
    var accept = document.getElementById(acceptButton);
    if(data correct)
    {
        do things..
    }
    else
    {
        accept.style.display = 'none';
    }
}

C#:

ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("Verify", "Verify.js");
this.FirstTextBox.Attributes.Add("onchange", string.Format("Valid('{0}', '{1}')",FirstTextBox.ClientID, AddButton.ClientID));

Hope that helps.

Upvotes: 3

Related Questions