Thursday, 1 October 2009

action script for creating a currency converter



//importing DataProvider class
import fl.data.DataProvider;

//creating a new data provider object
var dp:DataProvider = new DataProvider();
//first we create a variable to store the first value
var fromVal:Number;
//then we create a variable for the second value
var toVal:Number;
//here we store what the user inputs
var inputVal:Number
//the result value
var calculatedVal:Number;
//the user can enter only numbers in the TextInput
input_txt.restrict = "0-9";

//adding items to the Data Provider. The user sees the "label" property.
//For data we set the currency weight. US dollar has weight 1.
//The others are in proportion to US Dollar
dp.addItem( { label: "U.S. Dollars", data:1 });
dp.addItem( { label: "Australian Dollars", data: 0.832114 });
dp.addItem( { label: "Canada Dollars", data: 0.926215 } );
dp.addItem( { label: "Euro", data:1.42643 });
dp.addItem( { label: "United Kingdom Pounds", data:1.65151 });
dp.addItem( { label: "India Rupees", data:0.0207573 });
dp.addItem( { label: "Poland Zlotych", data:0.341955 });
dp.addItem( { label: "Russia Rubles", data:0.0325614 });
dp.addItem( { label: "Philippines Pesos", data:0.02079 });
dp.addItem( { label: "Bulgarian Leva", data:0.729733 });
dp.addItem( { label: "Brazil Reais", data:0.531719 });

//populating the lists
fromList.dataProvider = dp;
toList.dataProvider = dp;

//adding Event Change listeners to all of the components
fromList.addEventListener(Event.CHANGE, calculateResult);
toList.addEventListener(Event.CHANGE, calculateResult);
input_txt.addEventListener(Event.CHANGE, calculateResult);
//we set items that are set by default
fromList.selectedIndex = 0;
toList.selectedIndex = 3;

//initializing "fromVal" and "toVal"
fromVal = fromList.selectedItem.data;
toVal = toList.selectedItem.data;

function calculateResult(e:Event):void{
fromVal = fromList.selectedItem.data;
toVal = toList.selectedItem.data;
//casting String to Number
inputVal = Number(input_txt.text);
//calculating the result
calculatedVal = inputVal * (fromVal / toVal);
//adding the result to the text field
result_txt.text = calculatedVal.toString();
}

No comments: