user5508297
user5508297

Reputation: 885

Using the required attribute on a password input

I'm trying to set a password input as required in JavaScript.

I have learnt from this post how to do it but it doesn't seem to work with my password input.

<div class = "login">
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</div>
var p = document.querySelector(".enterPassword");
p.required = true;
p.style.backgroundColor = "gray";

var s = document.querySelector(".submit");
s.addEventListener("click", clickHandler.bind(p));

function clickHandler() {
    console.log("Password: " + this.value);
}

jsfiddle

Although I do,

var p = document.querySelector(".enterPassword");
p.required = true;

as you can see, there is no required popup when a user fails to enter a password. Does anyone know why not?

Upvotes: 0

Views: 88

Answers (1)

brk
brk

Reputation: 50291

Wrap the elements in a form

<form>
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</form>

You can also check it without using form

document.querySelector(".enterPassword").validity.valid

this will return a Boolean value , but you wont see the error pop up

JSFIDDLE

Upvotes: 3

Related Questions