jQuery interprets NULL parameter to val() call as no parameter

I tried to be smart (no, I was not obfuscating my code) and squeeze the following algorithm into one line of code:

  • Set the field email to the value of cookie user
  • If the cookie user is not present, focus the email field, otherwise focus the pwd field.

The one-liner I (almost) got working is:

if ($("#email").focus().val($.cookies.get("user")).val()) $("#pwd").focus();

The description of how this beast works is left as an exercise for the reader

However, the $.cookies.get function returns NULL if the cookie is not set and the first val call interprets the NULL value as no parameter, returning the current value of the field, not the chainable jQuery object.

Too bad, I had to write two lines of code:

$("#email").focus().val($.cookies.get("user"));
if($("#email").val()) $("#pwd").focus();

No comments:

Post a Comment