JavaScript

How to check if an input field is empty in Javascript

In this tutorial, we are going to see how to check if an input field is empty or not in JavaScript. Often, users fill out one or more fields on an HTML form before submitting it. You can write a JavaScript form validation script to check whether the required HTML form fields are empty or not.
 

Script to check if an input field is empty in Javascript
<html>
   <head>
      <script>
         function isEmpty(){
             var str = document.forms['myForm'].firstName.value;
             if( !str.replace(/\s+/, '').length ) {
                  alert( "The Name field is empty!" );
                  return false;
             }
         }
      </script>
   </head>
<body>
   <form name="myForm">
      Name: <input name="firstName" /> 
      <button onclick="return isEmpty()" type="submit" value>Submit</button>
   </form>
</body>
</html>
Result
Name:
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *