Creating textfields for user input
TextFields in Titanium are single-line textboxes used to capture user input via the keyboard, and usually form the most common UI element for user input in any application, along with labels and buttons. In this section, we'll show you how to create a Textfield, add it to your application's View, and use it to capture user input. We'll style our textfield component using a constant value for the first time.
How to do it...
Type the following code after the view has been created but before adding that view to your window. If you've been following along from the previous recipe, this code should be entered after your labels have been created:
//creating the textfield for our loan amount input var tfAmount = Ti.UI.createTextField({ width: 140, height: 30, right: 20, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Ti.UI.RETURNKEY_DONE, hintText: '1000.00' }); amountRow.add(tfAmount); //creating the textfield for our percentage interest //rate input var tfInterestRate = Ti.UI.createTextField({ width: 140, height: 30, right: 20, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Ti.UI.RETURNKEY_DONE, value: interestRate }); interestRateRow.add(tfInterestRate);
How it works...
In this example, we created a couple of basic textfield with a rounded border style, and introduced some new property types that don't appear in labels and imageviews, including hintText
. The hintText
property displays a value in the textfield, which disappears when that textfield has focus (for example, when a user taps it to enter some data using their keyboard).
The user input is available in the textfield property called value
; as you must have noted in the preceding recipe, accessing this value is simply a matter of assigning it to a variable (for example, var myName = txtFirstName.value
), or using the value
property directly.
There's more...
textfield are one of the most common components in any application, and in Titanium there are a couple of points and options to consider whenever you use them.
Retrieving text
It's important to note that when you want to retrieve the text that a user has typed in a textfield, you need to reference the value
property and not the text, like many of the other string-based controls!
Experimenting with other textfield border styles
Try experimenting with other textfield border styles to give your app a different appearance. Other possible values are the following:
Ti.UI.INPUT_BORDERSTYLE_BEZEL Ti.UI.INPUT_BORDERSTYLE_LINE Ti.UI.INPUT_BORDERSTYLE_NONE Ti.UI.INPUT_BORDERSTYLE_ROUNDED