How to Check Required Fields on Form Submit [JavaScript]

Say you have an HTML form contain multiple fields – a mix of textarea, text input, radio button, drop downs (SELECT) and/or check boxes – and some of these fields are required. That is, if the user submits the forms, the browser should display an alert (or an inline message) saying that required fields are missing.

How do you check the submitted form for missing fields? There’s an easy way. Wrap all the required form fields in the HTML with the “ss-item-required” class as show below:

    <div class="ss-item-required">
      <label>Question: What is your name?</label>
      <input type="text" name="name" id="name"></input>
    <div class="ss-item-not-required">
      <label>Question: What is your email?</label>
      <input type="text" name="email" id="email"></input>
    <div class="ss-item-required">
      <label>Question: What is your address?</label>
      <textarea name="address" rows="8" cols="75" id="address"></textarea>
    <div class="ss-item-required">
      <label>What is your sex?</label>
       <input type="radio" name="sex" value="male">Male
       <input type="radio" name="sex" value="female">Female

    <a href="#" onclick="formcheck(); return false">Submit</a>

As you can see, the above form has four fields and except for the email address, all fields are required. Next we write a simple JavaScript function that will execute when the user submits the form.

function formcheck() {
  var fields = $(".ss-item-required")
        .find("select, textarea, input").serializeArray();
  $.each(fields, function(i, field) {
    if (!field.value)
      alert( + ' is required');

The .serializeArray jQuery function will put all the filled form values into an Array. We are limiting this array to “required” fields only by using the find() function with the item selector.

Next, we iterate through all the fields in the array and if anyone is blank (or has no value), the user is alerted with a message box.

The last console.log will print the content of the form in the Console windows thus making it easy for you to debug input fields. Please note that this only check for missing fields but does not validate the user input.