yosimba2000
yosimba2000

Reputation: 91

Jquery Client-Side Form Validation

I just found out that using Jquery for form submission also means I need to use Jquery for client-side validation as well. I have done some research and found the reportValidity() function which does everything I need it to do, but I am not clear on what the code does.

My question is on the [0] in $("#loginemail")[0]

$("#loginbutton").click(function() {
  if ($("#loginemail")[0].reportValidity()) {
    alert("login email is valid");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="email" placeholder="Email Address" id="loginemail" autofocus required><br>
<input type="email" placeholder="Email Address" id="loginemail" required><br>
<input type="button" value="Log In" id="loginbutton"></br>

I read that when Jquery is told to use the selector, say for an id, it will find all instances of that id and make an array. The [#] is to clarify to Jquery which id to act upon. You can see that I have two email fields, each with the same id of 'loginemail'.

When the index is set to [0], filling in the first email box and clicking Log In results in a successful alert.

However, when the index is set to [1], this means Jquery should be acting on the 2nd email box. When I fill in the 2nd email box correctly, the alert does not show. Why is this?

Upvotes: 1

Views: 69

Answers (1)

Quentin
Quentin

Reputation: 943579

An ID must be unique in a document. Use a markup valitor to fix errors in your HTML.

The selectors API optimises searching for ID selectors by assuming your document is not invalid (and stopping after it finds a single match).

(It doesn't perform that optimisation for an ID attribute selector, but you should fix the HTML instead of hacking around the problem. Use a class instead.)

Upvotes: 1

Related Questions