How to check if the input is empty with jQuery
In this tutorial, we are going to see how to check if the input is empty with jQuery. You can simply use the method val() to check if the inputs are empty in jQuery.
The following example will show a red outline around the inputs if they are selected but not filled.
How to check if the input is empty with jQuery
<!DOCTYPE html> <html> <head> <title>Check if the input is empty with jQuery</title> <style> .error{ outline: 1px solid #f00; } </style> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(document).ready(function(){ $('#frm input[type="text"]').blur(function(){ if(!$(this).val()){ $(this).addClass("error"); } else{ $(this).removeClass("error"); } }); }); </script> </head> <body> <form id="frm"> <p><label>Firstname: <input type="text"></label></p> <p><label>Lastname: <input type="text"></label></p> <p><label>Address: <input type="text"></label></p> </form> </body> </html>
Result |
---|