jQuery: why an empty text field cannot be null

There's a widespread tendency to consider the value property of a text field as an attribute instead of a simple property whose value is a string. Such property cannot have a primitive null value because the DOM specifications allow only nodes to have such a value. jQuery wraps the value property with its method val() and it uses the same principles. Let's see why an empty value of a text field cannot be null.

value is not an attribute node, but a property whose value is a string (string). So if you test this property against the null value, you won't get what you expect because this value applies to DOM nodes. For example:

<form action="#" method="get" id="test">
		<input type="text" name="q" id="q" />
		<input type="submit" value="Search" />

We can run the following test, using both jQuery and the DOM:

$(function() {

	$('#test').submit(function(event) {
		var $form = $(this);
		var value = $('#q', $form).val();
		var value2 = document.getElementById('q').value;
		console.log(typeof value); // string
		console.log(typeof value2); // string


Either the text field has a value or not, the final result is always a string. So this is the correct check:

if(value == '' || value.length == 0) {

	// message


Comments are closed.