user1434156
user1434156

Reputation:

Count elements with class `.errror`

I am using abide from foundation zurb to validate inputs from the client side. I have 4 input fields that are being validated through js. I am using jquery to count .error after submit button click but I am getting unexpected values returned. After clicking the submit button twice the number of .errors shows count 8 even if there is only just 4 .errors fields. How can I display number of .errors that are visible in the form? LINK

<script>
      var $error_items = 0;
      $("#submit").click(function(e){
        $error_items = $(".error").length;
        alert($error_items);
      });
    </script>

HMTL

<form data-abide>
              <div class="name-field">
                <label>Your name <small>required</small>
                  <input type="text" required pattern="[a-zA-Z]+">
                </label>
                <small class="error">Name is required and must be a string.</small>
              </div>
              <div class="name-field">
                <label>User name <small>required</small>
                  <input type="text" name="users_name" required pattern="[a-zA-Z]+">
                </label>
                <small class="error">Username is required and must be a string.</small>
              </div>
              <div class="email-field">
                <label>Email <small>required</small>
                  <input type="email" required>
                </label>
                <small class="error">An email address is required.</small>
              </div>
              <div class="password-field">
                <label>Password <small>required</small>
                  <input type="password" id="password" required pattern="password">
                </label>
                <small class="error">Your password must match the requirements</small>
              </div>

              <button type="submit" id="submit">Submit</button>
            </form>

Upvotes: 0

Views: 202

Answers (2)

pdjota
pdjota

Reputation: 3243

You may count only the visible error labels using visible selector for instance:

$('small.error:visible').length

Upvotes: 0

James Montagne
James Montagne

Reputation: 78710

If you inspect the DOM after clicking the submit button, you will see the following for each of your error labels:

<label class="error"></label>    
<small class="error"></small>

One added by you initially and the other added dynamically once the submit button is clicked. The count of 8 is correct.

You may just want to count label.error as that seems to be what you are trying to count.

Upvotes: 1

Related Questions