I wanted to create a US zipcode TextField in Titanium for a mobile app. In this case the app was going against a database with only 5 digit zip codes. So I needed to prevent the phone keyboard from allowing more than 5 digits.
The TextField class provides the way to limit the keyboard to just numbers by setting the keyboardType property to Titanium.UI.KEYBOARD_NUMBER_PAD. However it does not have a property to limit the maximum characters.
The solution is to use the TextField change event. This event is fired when the characters change in the TextField. The handler for the TextField change event provides a dynamic reference to the TextField so the properties are exposed. This way we can use the handler for other TextFields assuming they have the same requirement when a change occurs.
The value property of the TextField can be truncated of any additional characters fover a limit with a simple line of code.
[ad name=”Google Adsense”]
Here is a snippet of the code you need. The properties such as top and left you can adjust to your layout needs. Line 12 is how the TextField is limited to number entry.
The change handler is on line 17. Line 19 shows using the slice method to chop off characters. In this example it is resetting the TextField value property to its own characters starting with character 0 and taking the next five.
If you want to improve the coding, you can create a constant to hold the limit value instead of burying the bare number into the handler function.
// Textfield for 5 digit zip code var zip_tf = Titanium.UI.createTextField({ color:'#000', font:{ fontFamily:'Helvetica Neue', fontSize:15 }, height:35, top:10, left:80, width:60, keyboardType:Titanium.UI.KEYBOARD_NUMBER_PAD, returnKeyType:Titanium.UI.RETURNKEY_DEFAULT, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED }); // Handler for zip_tf change event. zip_tf.addEventListener('change', function(e) { e.source.value = e.source.value.slice(0,5); });
[ad name=”Google Adsense”]