1

I'm building a set of text boxes from asp.net repeater and trying to add a key down event from C# code to those text boxes to prevent user from entering a specific character (comma(,)). I can't use the text box id itself in Javascript because its built dynamically with diff id's. Now I have no idea how to pass the e object to the textbox's keydown event from C#.

Any suggestion is much appreciated.

Code Snippet :

 TextBox txtTextField = e.Item.FindControl("txtAns_1") as TextBox;
 txtTextField.Attributes.Add("keydown", "PreventChars(" + txtTextField +")");

Javascript

   function PreventChars(e) {

            var k = String.fromCharCode(e.which);

            if (k.match(/,/g))
            {
                e.preventDefault();
            }

        };

1 Answer 1

1

use ClientID

ClientID returns The control ID for HTML markup that is generated by ASP.NET.

Change Code Snippet to:

TextBox txtTextField = e.Item.FindControl("txtAns_1") as TextBox;
txtTextField.Attributes.Add("keydown", "PreventChars(" + txtTextField.ClientID +")");
Sign up to request clarification or add additional context in comments.

1 Comment

To be honest, I don't exactly understand how passing the ClientID as an object works, but it does work. You need to dig a bit on the front-end to get the event argument but you can find it under e.keydown.arguments[0].key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.