We can use jQuery to check if an input value is empty by using the val() method and the JavaScript length property. We simply get the value of the input using the val() method, and then check to see if its length is greater than 0.
if ($("input").val().length > 0) {
// input is NOT empty
} else {
// input IS empty
}
If you are using WordPress, don’t forget to change the $ to jQuery as below:
if (jQuery("input").val().length > 0) {
// input is Not empty
} else {
// input is empty
}
An example of using jQuery to check if an input is empty on a form
Below we will have a simple form with a name field and a submit button. One thing that is common in a lot of online forms is making sure the input fields are filled out before allowing the user to submit the form.
So below we will have a form that only lets you submit the information if you enter in a name in the name input box. Here is the HTML code:
We will use the jQuery val() method to get the value of the input and then use the JavaScript length property to see if the input is empty or not.
We will finally use jQuery to disable or enable the submit button based on whether a name exist or not. The submit button will start as disabled, and once someone starts typing a name, we will enable the button. We will do this using the jQuery keyup() method.
Here is the code:
$('#fname').keyup(function(){
if ($("#fname").val().length > 0) {
// input is Not empty, enable button
$('button').prop('disabled', false);
} else {
// input is empty, disable button
$('button').prop('disabled', true);
}
});
The final code and output for this example of checking if an input value is empty is below:
Code Output:
Full Code:
<script>
$('#fname').keyup(function(){
if ($("#fname").val().length > 0) {
// input is Not empty, enable button
$('button').prop('disabled', false);
} else {
// input is empty, disable button
$('button').prop('disabled', true);
}
});
</script>