Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

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:

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

   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:

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

DynamicModule[{symbol = ""},
   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?

share|improve this question

marked as duplicate by Kuba, Yves Klett, Sjoerd C. de Vries, Artes, R. M. Dec 7 '13 at 7:44

This question was marked as an exact duplicate of an existing question.

it's a simple mistake: Dynamic@foo[symbol], Dynamic gives head. Try StringQ[Dynamic["test"]] – Kuba Dec 6 '13 at 15:56
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... – Albert Retey Dec 7 '13 at 11:21

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},
   Row[{"Text field:", InputField[Dynamic[symbol], String]}],
 Initialization :> {foo[t_] := 
    If[StringQ[t], {t, "defined"}, {t, "undefined"}]}
share|improve this answer

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