jQuery

Check if Textbox is Empty using jQuery Examples

Have you ever wondered how to check if Textbox is Empty using jQuery? In this article, I am going to share a very easy way that you can use to check if Textbox is Empty using jQuery.

How to check if Textbox is Empty using jQuery

For this example, I am assuming that we have a Textbox in a form and we need to check if this textbox is empty or not when the “Check” button is clicked. The following is the complete source code:

Example: Use jQuery to check if textbox is empty

<html>
<head>
<title>jQuery Textbox Empty | How to check if Textbox is Empty using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>

<form name="form1" method="post" action="">
<label for="city">City:</label>
<input type="text" name="city" id="city">
</form>
<button id="check">Check</button>

<script type="text/javascript">

$('#check').click(function() {

if ( $('#city').val() == '' )
{
	alert('Empty!!!');
}
else
{
	alert('Contains: ' + $('#city').val() );
}

});

</script>
</body>
</html>

Once you run the above code and click the “Check” button, the page will alert “Empty!!!”. If you enter something in it and then click the button, it will show the value you entered.

Simple, isn’t it?

Do you know of any other ways to check if textbox is empty using jQuery? Feel free to suggest by commenting below.

2 Comments on Check if Textbox is Empty using jQuery Examples

  1. 1

    another way:

    if ( $(‘#city’).is(‘:empty’ ) {

    also, jsHint keeps encouraging me to use === rather than == for comparison…

    Tx!

Share your thoughts, comment below now!

*

*