0
$\begingroup$

I'm having trouble detecting when my InputForm supplied String variable has a value. After looking at:

How to compute values only if input fields are filled?

I tried a StringQ test:

Clear[foo]
foo[t_] := If [ StringQ[t], {t, "defined"}, {t, "undefined"} ]

DynamicModule[{symbol},
 Column[{
   Row[{"Text field:", InputField[Dynamic[symbol], String]}],
   foo[ Dynamic[symbol] ]
   } ]
 ]

Before the field is supplied this gives me what I expected:

before field keyed

but after keying the field, I see that my test hasn't worked:

after keying text

Based on

How can I make sure all InputFields have values before processing a nb form?

I tried:

Clear[foo]
foo[t_] := If [ !Equal[t, ""], {t, "defined"}, {t, "undefined"} ]

DynamicModule[{symbol = ""},
 Column[{
   Row[{"Text field:", InputField[Dynamic[symbol], String]}],
   foo[ Dynamic[symbol] ]
   } ]
 ]

but this produces a kind of odd unevaluated If block:

other try

I'm clearly doing something wrong with how I'm testing or using the input variable or form, but it's not obvious to me what that is?

$\endgroup$
2
  • $\begingroup$ it's a simple mistake: Dynamic@foo[symbol], Dynamic gives head. Try StringQ[Dynamic["test"]] $\endgroup$
    – Kuba
    Dec 6, 2013 at 15:56
  • $\begingroup$ I agree that this is a duplicate, but the issue seems to be the wrong use of Dynamic, the code will do what is expected when using Dynamic[foo[symbol]] instead of foo[Dynamic[symbol]] and that isn't explained in the linked duplicate question IMO. The best answer I could find seems to be John Fultz's to this question, which I think would be a better duplicate link, but probably someone knows a good candidate on ME... $\endgroup$ Dec 7, 2013 at 11:21

1 Answer 1

0
$\begingroup$

As canvassed often here it is better practice to stick your functions in initialization. Additionally it is best to think about Dynamic as updating pixels on the screen. So find the expression that gets rendered on the screen and then wrap it in Dynamic. The code below works fine:

DynamicModule[{symbol = Null},
 Column[{
   Row[{"Text field:", InputField[Dynamic[symbol], String]}],
   Dynamic@foo[symbol]
   }],
 Initialization :> {foo[t_] := 
    If[StringQ[t], {t, "defined"}, {t, "undefined"}]}
 ]
$\endgroup$

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