How Do I Determine If a Password Text Box Has Focus?

I’m having a problem determining if a given control has focus. It seems to me that:

if (form.password.focus() == true) ...

should determine if the form’s password control has focus. But, it’s returning “false” even while I’m typing into the control.

So, what is the correct way to determine whether a control has focus? It seems to involve the onfocus event, but I really do not understand the process.

Thank you very much!

Hi there AARRGGHHH,

does this help…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 100% / 160% verdana, arial, helvetica, sans-serif;
 }
label {
    cursor: pointer;
 }
</style>

</head>
<body> 
 <form action="#">
  <label for="password">password: </label>
  <input type="password" id="password" name="password" required>
 </form>

<script>
 ( function( d ) {
   'use strict';

    var pswd = d.getElementById( 'password' );

   pswd.addEventListener( 'focus', 
      function() {
         if( pswd.focus ) {
            console.log( 'password has focus' );
            }
         },false);

   pswd.addEventListener( 'blur', 
      function() {
         if( this.blur ) {
            console.log( 'password does not have focus' );
            }
         },false);
 }( document ));
</script>

</body>
</html>

coothead

Nope.

[quote=“AARRGGHHH, post:1, topic:294055, full:true”]
I’m having a problem determining if a given control has focus.[/quote]

You can check document.activeElement which gives the currently focused element.

Hi Paul

When I try alert(document.activeElement) I get [object HTMLInputElement]. So I thought that

if (HTMLInputElement("password") == true)...  

might work, but it didn’t. How do I find out which “HTMLInputElement” has the focus? I’m lost on the syntax.

Thank you

[quote=“AARRGGHHH, post:5, topic:294055, full:true”]
When I try alert(document.activeElement) I get [object HTMLInputElement].[/quote]

You can get different properties on the object, such as type, name, etc. to check if they match known values, such as “password” for the type.

Okay, I’ll try

`if (document.activeElement.id == password1)...` 

and

`if (document.activeElement.name == password1)... 

Thank you very much.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.