in Appcelerator Titanium

Tabbing Through a Form in Titanium

I saw a recent post on Appcelerator Q&A asking if it were possible to simulate the ‘tab’ key functionality for moving the focus down to the next text field in a form, as opposed to having to manually set an event listener on each text field to listen for the ‘return’ key to be pressed, then setting the focus on the next field.  I’m not sure if the tab option is possible in Ti, but we can automate the latter option a bit by keeping track of our fields in an array.

To move the cursor or focus on an app to a specific text field, we do FieldName.focus();  So, to move focus from one field to the next when a user hits the return key, we use an event listener, like this:

FieldName1.addEventListener('return', function(){
    FieldName2.focus();
});

Doing this for a bunch of fields in a form could be cumbersome, so one option would be to save all the fields in an array and just track where you are at in the array and move to the next field.  Easier to show the code then explain it:

Ti.UI.setBackgroundColor('#000');
 
var win = Titanium.UI.createWindow({
    title : 'test'
});
 
var arrayLength = 5
var fields = new Array(arrayLength);
 
for( i = 0; i < arrayLength; i++) {
    fields[i] = Ti.UI.createTextField({
        id : i,
        height : 40,
        width : 100,
        hintText : 'Field ' + i,
        value : '',
        top : i * 50,
        returnKeyType : i != arrayLength - 1 ? Titanium.UI.RETURNKEY_NEXT : Ti.UI.RETURNKEY_DONE,
        borderStyle : Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
    });
 
    fields[i].addEventListener('return', function(e) {
        var j = e.source.id;
 
        if(j != arrayLength-1) {
            fields[j + 1].focus();
        } else {
            alert('Done');
        }
 
    });
    win.add(fields[i]);
};
 
win.open();

Gist here.

Here I am also doing some simple enhancements by renaming the return key to ‘Next’ or ‘Done’ depending on if it is the last field in the form, as well as handling the event differently for the last ‘Done’ click. In the event listener, we could also do some validation or form submission as well.

Another option would be to use a table view or a web view and just write the code in HTML. The latter is actually discussed as an option in the Titanium Certified Mobile Developer Training course. Check it out here.