New to Telerik UI for ASP.NET AJAX? Start a free 30-day trial
Dynamically Adjusting Height of RadTextBox Based on User Input
Environment
Product | Telerik® UI for ASP.NET AJAX RadTextBox |
Version | All |
Description
I want to dynamically adjust the height of a RadTextBox control based on the number of lines entered by the user. My goal is to avoid vertical scrollbars while maintaining a fixed width of 400px.
Solution
To dynamically adjust the height of the RadTextBox control, use the OnValueChanged
client-side event. Attach JavaScript logic to resize the text area as users type. The following example demonstrates how to achieve this:
Example
Markup:
ASP.NET
<telerik:RadTextBox ID="txtComment" runat="server" MaxLength="1024" Rows="5" TextMode="MultiLine" Width="400px">
<ClientEvents OnValueChanged="onValueChanged" />
</telerik:RadTextBox>
JavaScript
function onValueChanged(sender, args) {
let textArea = sender.get_element();
function resize() {
textArea.style.height = 'auto'; // Reset height
textArea.style.height = textArea.scrollHeight + 'px'; // Adjust to content height
}
textArea.addEventListener('input', resize);
}
Steps:
- Add the
OnValueChanged
client event to the RadTextBox. - Implement the
resize()
function in JavaScript. It resets the height of the text area and adjusts it to match its scroll height. - Use the
input
event listener to trigger theresize()
function whenever the user types.
This ensures the height dynamically updates based on the content entered by the user, avoiding vertical scrollbars while keeping the width fixed.