Reputation: 1367
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
Reputation: 2258
You should use onchange instead of OnTextChanged which is Server Side event.
Upvotes: 1
Reputation:
I think there are two issues here:
OnTextChanged
this should be updated to onchange
or onkeypress
depending on the responsiveness you are looking for.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