Check whether an input text box is empty with JavaScript/jQuery
This post will discuss how to check whether an input text box is empty in JavaScript and jQuery.
1. Using jQuery
To check if the input text box is empty using jQuery, you can use the .val() method. It returns the value of a form element and undefined on an empty collection.
jQuery
|
1 2 3 4 5 6 7 |
$(document).ready(function() { $('#submit').click(function() { if (!$('#name').val()) { alert('Enter your name!'); } }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> </div> <button id="submit">Submit</button> |
Using the .length property, you can do like:
|
1 2 3 4 5 6 7 |
$(document).ready(function() { $('#submit').click(function() { if ($('#name').val().length === 0) { alert('Enter your name!'); } }) }); |
2. Using JavaScript
With plain JavaScript, you can check the value of the value attribute of the input box to determine whether it is empty.
JS
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { $('#submit').click(function() { var value = document.getElementById('name').value; if (value === '') { alert('Enter your name'); } }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> </div> <button id="submit">Submit</button> |
That’s all about determining whether an input text box is empty in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)