actionscript-3apache-flexflex4flex4.6flex-mobile

Enable Button only when 2 TextInput fields are not empty - code and screenshot attached


In a Flex mobile app (or any Flex 4 application) - how can you enable/disable a button depending on the contents of 2 other fields?

enter image description here

I am pasting my very simple test code below and the problem with it is the syntax error in Flash Builder 4.7: The entity name must immediately follow the '&' in the entity reference. - which probably means that ampersand is a special character, but how to solve this (probably frequent) problem?

TestApp.mxml:

<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication 
    xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    firstView="views.Home" 
    applicationDPI="160">
</s:ViewNavigatorApplication>

views/Home.mxml:

<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009" 
        xmlns:s="library://ns.adobe.com/flex/spark" 
        title="How to enable Login button?">

    <s:layout>
        <s:VerticalLayout paddingTop="8"
            horizontalAlign="center" gap="8" />
    </s:layout>

    <s:Label text="Username:" />
    <s:TextInput id="_username" />
    <s:Label text="Password:" />
    <s:TextInput id="_password" />

    <s:Button id="_login" 
              label="Login" 
              enabled="{_username.text.length > 0 && _password.text.length > 0}" />
</s:View>

Solution

  • You shall replace && with &amp;&amp; when you write it outside of CDATA in mxml.

    It is also better to use _username.text!='' instead of _username.text.length > 0 because it will cause warnings at runtime as text is not an eventdispatcher and it can't report length changes. However, it will update button's availablity because text will be changed itself and TextInput will report it causing binding update.