Check if TextBox is Empty using JavaScript

Introduction: Hello Guys, “Welcome back” Today i am here with another one new great article. In this article I will explain about how to check if TextBox is Empty using JavaScript. When user will click on the Validate Button, JavaScript function will be called and the TextBox is referenced and its value is compared with Empty string and if the condition will be TRUE then the TextBox is considered Empty.

Code for HTML page

Implementation:On HTML page there will be two controls one is Textbox with the id named txt_name  for entering Text by the user.  Other control will be Button with the id named btn_check. On the OnClick event handler of the Button, I will call function named validate_value().

<input type="text" id="txt_name" />

<input type="button" id="btn_check" value="Check Empty" onclick="return validate_value()" />

 JavaScript Code

When the user will click on the Validate Button, the validate_value JavaScript function will be called. Inside the function, first the TextBox is referenced using JavaScript and then its value is trimmed and compared with an Empty string. Here I am using function trim is an inbuilt JavaScript function and is supported in all Modern or latest browsers only. If the condition tests TRUE, the TextBox is considered Empty and a JavaScript Alert Message will be displayed on the screen. And FALSE value will be returned in order to cancel event circulation.

<script type="text/javascript">

    function validate_value() {

        if (document.getElementById("txt_name").value.trim() == "") {

            alert("Please enter your Name!");

            return false;

        }

    };

</script>

Here I am giving complete code for HTML page with JavaScript functions as well as controls. You need to copy and paste the code in your HTML page for enjoying the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

</head>

<body>

    <input type="text" id="txt_name" />

    <input type="button" id="btn_check" value="Check Empty" onclick="return validate_value()" />

    <script type="text/javascript">

        function validate_value() {

            if (document.getElementById("txt_name").value.trim() == "") {

                alert("Please enter your Name!");

                return false;

            }

        };

    </script>

</body>

</html>

Conclusion: In above code, I have been explained that how to check if TextBox is Empty using JavaScript. This code is very helpful for every developer. Bye Bye and take care of yourself Developers. We will come back shortly with the new article.

 

Regards

Using Asp.net

 

 

 

Comments

Popular posts from this blog

Sending reset password link for one time use only in asp.net

add delete update inside gridview using store procedure in ASP.NET

Change password using asp.net