Reputation: 6792
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
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
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
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
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
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