We can check if a string is empty by using an if else conditional statement, and then use JavaScript to do something with this information. This is our preferred method to use.

var someString = "";
if (someString) {
  // The string is NOT empty
} else {
  // The string IS empty
}

You can also check if a string is empty by using the === operator and compare it to an empty string.

var someString = "";
if (someString === "") {
  // The string IS empty
} else {
  // The string is NOT empty
}

An example of using JavaScript to check if the string in 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 value property along with the getElementById method to get the value of the input. We will then have an if else statement to check if the input value is empty or not. If the value is not empty, we will enable the button to be clicked.

We will finally use JavaScript 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 with the help of the onkeyup event.

Here is the code:

function checkString(){
  if (document.getElementById("fname").value) {
    // input is Not empty, enable button
    document.getElementById("button1").disabled = false;
  } else {
    // input is empty, disable button
    document.getElementById("button1").disabled = true;
  }
};

The final code and output for this example of checking if an input string value is empty is below:

Code Output:




Full Code:

<script> function checkString(){ if (document.getElementById("fname").value) { // input is Not empty, enable button document.getElementById("button1").disabled = false; } else { // input is empty, disable button document.getElementById("button1").disabled = true; } }; </script>

Categorized in:

JavaScript,

Last Update: March 20, 2024