TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript JavaScript Is a String Var Empty or Null

JavaScript Is a String Var Empty or Null

PDF
User Rating: / 1
PoorBest 

This is a common question, this proves useful when you want to validate a form to ensure all fields are filled. The first example compares the variables length to 0 and its value to null, this is because a null string (a string with no content e.g. var myVar = "";) is not equal to a string with value set to null.

if ((myVar.value.length==0) || (myVar.value==null)){
	alert('myVar is null');
}else{
	alert('myVar = '+myVar);
}

To make this piece of functionality reusable we will create a utility method in JavaScript which we will call function isEmpty(). This will take a var as an argument and will return a boolean true|false depending on whether it is empty or not.

function isEmpty(testVar){
	if ((myVar.value.length==0) || (myVar.value==null)){
		return true;
	}else{
		return false;
	}
}

We can then use this to tests the html input page elements, using a simple call to the javascript:isEmpty(document.getElementById('email')). This JavaScript call can be assigned to the onclick() event handler on any page element. In the case of an input button it would be as follows.

<script type="text/javascript">
function isEmpty(testVar){
	if ((testVar.value.length==0) || (testVar.value==null)){
		return true;
	}else{
		return false;
	}
}

function elementValues(){
	if(isEmpty(document.getElementById('email'))){
		alert('email is empty or null');
	}else{
		alert('email is not empty\nemail = '+document.getElementById('email').value);
	}
}


<ol>
<li>With no value in the text box click the <b>Test button this will return that the value is empty or null.
<li>With any value in the text box click the <b>Test button this will return that value.

<input type="text" id="email" value=""/>

<input type="button" value="test"  onclick="javascript:elementValues()" />

Example:

  1. With no value in the text box click the Test button this will return that the value is empty or null.
  2. With any value in the text box click the Test button this will return that value.

Email: