Nick
Nick

Reputation: 5440

Using "null" in jQuery functions. Is this okay?

My database consists of some entries which are null (so they don't affect max, min, etc..). When I pull all of the data from the database, I need to repopulate form fields with the values. Using .val(value) where value = null seems to work without any problems, but I'm not sure if this is a valid way to go about this. It doesn't say anything in the jQuery documentation (that I can find) about using null as parameters to functions.

Edit: Changed NULL to null. I was still in PHP mode and that was a typo.

Upvotes: 2

Views: 1219

Answers (3)

user166390
user166390

Reputation:

NULL a JavaScript identifier (e.g. you can do var NULL = "foobar"). null is the JavaScript literal which evaluates to null. (See comments). Its value is "the sole value of the Null type."

Some (but not all) places in jQuery will behave the same if you pass in null or another falsey value such as "" (null is one of the false values in JS). You need to check the specific function documentation to see what the domain of the function is (e.g. what the accepted input values are).

EDIT: Edited by Matthew Flaschen to reflect comments

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

This will vary per-function and you should check each one carefully before using it (which of course you do anyway, right?!) to ensure that it behaves in the manner that you expect, but yes, jQuery "works" with null.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630559

Different functions handle it in different ways, but for .val() specifically, yes, this is perfectly valid:

$(".selector").val(null);

If you look at the .val() source, you can see null is converted to an empty string, "" before it's used:

if ( val == null ) {
  val = "";
}

Upvotes: 2

Related Questions