# Evaluating an If expression inside Dynamic

I was trying to display some value inside a InputField. Usually it looks like this:

DynamicModule[{a=1,b=20,fuc="1"},
Deploy[Style[Panel[
Grid[Transpose[{
{"Input Format","Value"},
InputField[Dynamic[a],Number,Enabled->Dynamic[fuc=="1"]]}
}], Alignment->Right], ImageMargins->10]]]]


However I wanted to change what is displayed in InputField according to what fuc is. I was trying to put If[] inside Dynamic. But it failed:

DynamicModule[{a=1,b=20,fuc="1"},
Deploy[Style[Panel[
Grid[Transpose[{
{"Input Format","Value"},
InputField[Dynamic[If[fuc=="1",a,b]],Number,Enabled->Dynamic[fuc=="1"]]}
}], Alignment->Right], ImageMargins->10]]]]


I can not change the value of a in the InputField even if fuc is chosen to be "1". The error message says:

Set::write: "Tag If in If[True,FEa$$570,FEb$$570] is Protected."


Any idea how to solve this problem? I do need some if logic in InputField! Thanks

• I see i have to move If out side – bboczeng Jul 4 '14 at 7:24

Update. Thanks to Eldo, Dynamic is needed outside the InputField.

DynamicModule[{a = 1, b = 20, fuc = "1"},
Deploy[Style[Panel[Grid[Transpose[
{
{"Input Format", "Value"},
Dynamic@InputField[
If[fuc == "1", a, b],
Number,
Enabled -> Dynamic[fuc == "1"]
]
}
}
],
Alignment -> Right]
, ImageMargins -> 10
]
]
]]

• I think InputField should display 20 when "2" is selected. If this is the case you have to write Dynamic@InputField[...] – eldo Jul 4 '14 at 12:45
• @eldo, you are right. Will correct, thanks. – Nasser Jul 4 '14 at 13:01
• Nasser, do you understand why when a number is entered into the input field for a, it displays the new number, but a is not changed? (At least for me, Mac OS, V9.0.1.) – Michael E2 Jul 5 '14 at 20:00
• @MichaelE2 The first argument of InputField can only be a settable lhs if it's inside of a Dynamic (and, of course, that Dynamic has a sensible setting function). Otherwise, what the FE receives is literally the evaluated argument of the InputField which, in this case, would be InputField[1, Number, Enabled->Dynamic[fuc == "1"]]. The a is long gone. – John Fultz Jul 6 '14 at 23:07
• @JohnFultz Thanks. Of course. Sort of a "D'oh" moment for me. – Michael E2 Jul 6 '14 at 23:19

Here are two ways. One of them may be what the OP alluded to in a comment; in any case, I'll give a complete solution below.

First, using If inside one InputField: The trick here is to use the second argument of Dynamic.

DynamicModule[{a = 1, b = 20, fuc = "1"},
Deploy[Style[
Panel[Grid[
Transpose[{{"Input Format", "Value"},
InputField[
Dynamic[If[fuc == "1", a, b],
If[fuc == "1", a = #, b = #] &],
Number, Enabled -> Dynamic[fuc == "1"]]}}],
Alignment -> Right],
ImageMargins -> 10]]]]


Second, using If to switch between two InputFields: The trick here is to wrap If in Dynamic:

DynamicModule[{a = 1, b = 20, fuc = "1"},
Deploy[Style[
Panel[Grid[
Transpose[{{"Input Format", "Value"},

In both cases one can change the value of a and not of b.