Avg. Rating 5.0

Problem

I have an editable ComboBox which has a dataProvider with item labels of length greater than 50, however I need to limit the length of the user-defined label to 50, whether they type it, or it is selected from the dropDown.

Solution

Extend the ComboBox Class, adding a property to specify the maximum number of characters allowed for the TextInput.

Detailed explanation

package
{
    import mx.controls.ComboBox;
   
    public class ComboBoxWithMaxChars extends ComboBox
    {
        public function ComboBoxWithMaxChars()
        {
            super();
        }
       
        private var _maxCharsForTextInput:int;
       
        public function set maxCharsForTextInput(value:int):void
        {
            _maxCharsForTextInput = value;
           
            if (super.textInput != null && _maxCharsForTextInput > 0)
                super.textInput.maxChars = _maxCharsForTextInput;
        }
       
        public function get maxCharsForTextInput():int
        {
            return _maxCharsForTextInput;
        }
       

       // This function is called when an item is selected from the dropdown.
        override public function itemToLabel(item:Object):String
        {
            var label:String = super.itemToLabel(item);
           
            if (_maxCharsForTextInput > 0)
                label = label.substr(0, _maxCharsForTextInput);
           
            return label;
        }
    }
}

Report abuse

Related recipes