7
$\begingroup$

Suppose I want to build a simple currency converter like this one:

enter image description here

The functionality is straightforward: enter an amount in any field box, it gets converted into other currencies whose fields are then output boxes.

The problem is to use the same fields for input and output, the input field being the one you choose to enter data. Is there a way to do that?

$\endgroup$
1
  • 4
    $\begingroup$ Take a look at the second argument of Dynamic. You should be able to get something working with that $\endgroup$ Jan 8, 2015 at 1:00

1 Answer 1

7
$\begingroup$

Like Mike said in a comment, the key is to use the second argument of Dynamic. In this case I've built a function updateCurrencies which modifies a global variable currencies which holds an Association object with all the currency values in it.

currencies = <|
   "USDollars" -> 0,
   "Euros" -> 0,
   "BritishPounds" -> 0,
   "SwedishKronor" -> 0
   |>;

updateCurrencies[base_][value_, _] := currencies = AssociationMap[
   QuantityMagnitude@CurrencyConvert[Quantity[value, base], #] &, 
   Keys[currencies]
   ]

flag[country_] := Show[CountryData[country, "Flag"], ImageSize -> 40]

Grid[{
  {flag["USA"], InputField[Dynamic[currencies["USDollars"], updateCurrencies["USDollars"]], Number]},
  {flag["Britain"], InputField[Dynamic[currencies["BritishPounds"], updateCurrencies["BritishPounds"]], Number]},
  {flag["Sweden"], InputField[Dynamic[currencies["SwedishKronor"], updateCurrencies["SwedishKronor"]], Number]}
}, {Dividers -> All, Spacings -> 1.5 {1, 1}}]

currency converter demo

$\endgroup$
2
  • $\begingroup$ My version complains about |<...>|, are you using version 10? $\endgroup$
    – A.G.
    Jan 8, 2015 at 4:07
  • $\begingroup$ @A.G. Yes, Association is new in version 10. But note that Association is only used because of its suitable syntax. This can be implemented without Association in Mathematica 9, using the second argument of Dynamic as is done here. $\endgroup$
    – C. E.
    Jan 8, 2015 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.