0

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?

Community
  • 1
  • 1
user5508297
  • 805
  • 2
  • 9
  • 24
  • Your submit button isn't a real submit button. It's just a regular button. – 4castle Jul 27 '16 at 13:42
  • @4castle Does user2181397's answer below make it into a 'real' submit button? – user5508297 Jul 27 '16 at 13:47
  • 1
    Yes, it does. Because now they have a relationship through the form. Otherwise the button has no idea that it's supposed to validate the other input. A `div` has no semantic meaning. – 4castle Jul 27 '16 at 13:48

1 Answers1

3

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

brk
  • 48,835
  • 10
  • 56
  • 78
  • Is there a particular reason why you wrap the whole thing in a div? Would it be possible to do without the div and instead make form the outer element with this attribute: ` – user5508297 Jul 27 '16 at 13:52
  • 1
    Yes it can be done. There is no need of _ – brk Jul 27 '16 at 13:55
  • When I click my button, the webpage sometimes refreshes. How can I stop this from happening? @user2181397 – user5508297 Jul 30 '16 at 09:49