New to Telerik UI for ASP.NET AJAX? Start a free 30-day trial
Representing Comma-Separated List as Chips in RadChipList for ASP.NET AJAX
Updated over 6 months ago
Environment
| Product | RadChipList for ASP.NET AJAX |
| Version | All |
Description
I need to allow users to input values, like medical condition codes, in a text box and dynamically convert each value into a chip when followed by a comma. This functionality should reflect how Adobe Lightroom handles keywords for photos—users type a word followed by a comma, and it transforms into a chip. I also want to store and bind this data appropriately, considering the use of a comma-separated string.
This knowledge base article also answers the following questions:
- How to dynamically create chips in RadChipList for ASP.NET AJAX?
- How to convert user input into RadChipList items with a text box?
- How to bind data from RadChipList into a comma-separated string?
Solution
To achieve this functionality, use the RadChipList control alongside a RadTextBox to dynamically create chips each time the user enters a value followed by a comma. The createItem method of the RadChipList enables dynamic chip creation. Follow the steps below:
- Add a
RadTextBoxand aRadChipListto your page. - Use the
OnKeyPressclient-side event of theRadTextBoxto check for the comma character. - When a comma is detected, extract the input, create a chip using
createItem, and clear the text box for further input.
ASP.NET
<telerik:RadTextBox RenderMode="Lightweight" ID="RadTextBox1" runat="server">
<ClientEvents OnKeyPress="onKeyPress" />
</telerik:RadTextBox>
<telerik:RadChipList runat="server" ID="ChipList1" />
JavaScript
let itemsArray = [];
function onKeyPress(sender, args) {
if (args.get_keyCharacter() === ',') {
let code = sender.get_textBoxValue().trim(); // Get current input
if (code) {
let chipList = $find('<%= ChipList1.ClientID %>'); // Find RadChipList instance
let selectedChip = chipList.createItem(code); // Create a chip with the input text
itemsArray.push(selectedChip); // Add chip to array
chipList.set_items(itemsArray); // Update the chip list
setTimeout(() => {
sender.set_textBoxValue(""); // Clear the text box for new input
}, 10);
}
}
}
Explanation:
- The
OnKeyPressevent triggers each time a key is pressed within theRadTextBox. - The
args.get_keyCharacter()method checks if the pressed key is a comma. - The
createItemmethod dynamically creates a chip with the input text. - The
set_textBoxValue()method clears the text box after the chip is created.