TextFields in Titanium are single-line textboxes used for capturing 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 recipe we'll show you how to create a TextField, add it to your application's View, and use it to capture user input. We will style our TextField component by using a Constant value for the first time.
The complete source code for this recipe can be found in the /Chapter 1/Recipe 4
folder.
Type in the following code after the View is created but before we add that view to our Window. If you have been following along from the previous recipe, this code should be entered after your Labels were created:
//creating the textfield for our loan amount input var tfAmount = Titanium.UI.createTextField({ width: 140, height: 30, top: 100, right: 20, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Titanium.UI.RETURNKEY_DONE, hintText: '1000.00' }); view.add(tfAmount); //creating the textfield for our percentage interest //rate input var tfInterestRate = Titanium.UI.createTextField({ width: 140, height: 30, top: 150, right: 20, borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Titanium.UI.RETURNKEY_DONE, value: interestRate }); view.add(tfInterestRate);
In this example, we are creating a couple of basic TextFields with a rounded border style and introducing some new property types that don't appear in Labels and ImageViews including hintText
. The hintText
property displays a value in the TextField that 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's property called value
. As you will note in the previous recipe, accessing this value is simply a case of assigning it to a variable (that is var myName = txtFirstName.value
), or alternatively using the value property directly.
TextFields are one of the most common components in any application, and in Titanium, there are a couple of points and options to consider whenever using them.
It is important to note that when you want to retrieve the text a user has typed into a TextField, you need to reference the value
property and not text
, like many of the other string-based controls!
Try experimenting with other TextField border styles to give your app a different appearance. Other possible values are:
Titanium.UI.INPUT_BORDERSTYLE_BEZEL Titanium.UI.INPUT_BORDERSTYLE_LINE Titanium.UI.INPUT_BORDERSTYLE_NONE Titanium.UI.INPUT_BORDERSTYLE_ROUNDED