JavaScript

How To Check If Textbox Is Empty Using JavaScript

If you have worked with forms, then you would know how important it is to process the form input to make sure that all the required information is filled out properly. In this article, I am going to share a very easy way that you can use to check if Textbox is Empty using JavaScript.

How to use JavaScript to Check If Textbox Is Empty?

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.

Example: Check if Textbox has contents or if it is empty using JavaScript

<script Language="JavaScript">
<!--
function check_blank()
{
// If the value of the textbox is empty, then show an alert
if (my_form.state.value == "")
{
alert("Please fill in State.");

// Focus the textbox so that user can fill it
my_form.state.focus();

// return false to stop further processing
return false;
}

// If state is not null continue processing
return true;
}
-->
</script>

<form name="my_form" id="my_form" action="#" onsubmit="return check_blank();">
<label for="state">State</label>
<input type="text" name="state" id="state" >
<input type="submit" value="Check">
</form>

Once you run the above code and click the “Check” button, the page will show an alert. If you enter something in it and then click the button, the form will quietly submit the info.

Simple, isn’t it?

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

One Trackback

  1. 1

    […] Here is a quick and very easy example on how to check if Textbox is Empty using JavaScript. Try the demo to check if Textbox is Empty using JavaScript. – read more […]

Share your thoughts, comment below now!

*

*