Theomax
Theomax

Reputation: 6792

Is it considered bad practice if you use an <input> for a textbox compared to <asp:Textbox>?

I have an ASP.NET page that contains a form and a button. In order to use the OnKeyPress and a javascript function (to stop the user from using the enter key and without adding a FilteredTextBoxExtender) attribute I had to change the <asp:Textbox> to an <input> with type="text".

Is this considered bad practice? Or are there valid situtations where should be used?

To ensure this question isn't subjective - are there any other ways to prevent the user using the enter key when typing in an ASP.NET textbox? (without putting code in the code behind)

Upvotes: 0

Views: 216

Answers (5)

jbl
jbl

Reputation: 15413

You should just use the ClientID of your asp:TextBox here is an example using jQuery :

<asp:TextBox ID="inputTB" runat="server"></asp:TextBox>

<script language="javascript" type="text/javascript">
    $('#<%=inputTB.ClientID%>').keypress(function (e) {
        if (e.which == 13) // return key
        {
            return false;
        }
    });
</script>

Upvotes: 1

starskythehutch
starskythehutch

Reputation: 3338

You can add JavaScript to <asp:TextBox />. You can either attach the JavaScript using the ClientID of the control, or you can add it in the codebehind using

MyTextBox.Attributes.Add("onKeyPress", "myJavaScriptFunction()");

Upvotes: 1

Chris Dixon
Chris Dixon

Reputation: 9167

If you want your input to be accessed by .NET code-behind then it's considered best practice to use the TextBox control. You can put a runat=server on an input, but only when you must.

If it were me, I'd use the , add an ID and set the ClientIDMode="Static" if possible, or add a class with CssClass="class", then use jQuery to handle the onKeyPress even with something like this:

$('.class').on('change', function() {

});

Upvotes: 3

Oded
Oded

Reputation: 498934

You do not need to change the control type in order to use client side events in javascript.

The control has a ClientId property that can be used for binding the event to (using getElementById, for example).

Upvotes: 2

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

In General you should use Asp.Net control only when is strictly required ad the classic HTML are much faster as they don't need any server elaboration to be rendered

Upvotes: 3

Related Questions