Diablo3093
Diablo3093

Reputation: 1063

focus() is not working in javascript or jquery

I am trying to focus on an input element using javascript. This is the html.

<!DOCTYPE html>
<html>

<head>
  <style>
    input:focus {
      background-color: yellow;
    }
  </style>
</head>

<body>

  <p>Click inside the text fields to see a yellow background:</p>

  <form>
    First name: <input id="abc" type="text" name="firstname"><br>
  </form>

</body>

</html>

When I manually click using the mouse, I can see the yellow background. But when I run the code $('#abc').focus() or document.getElementById('abc').focus() I don't see the yellow background. How to simulate the mouse focus using javascript?

Upvotes: 0

Views: 357

Answers (3)

Here you have it working. Hope it helps.

$("#boton").click(function() {
  $("#abc").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <style>
    input:focus {
      background-color: yellow;
    }
  </style>
</head>

<body>

  <p>Click inside the text fields to see a yellow background:</p>

  <form>
    First name: <input id="abc" type="text" name="firstname"><br>
  </form>
  <button id="boton"> Click Me to focus
</button>

</body>

</html>

Upvotes: 0

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

I don't know what you are doing wrong, but accessing the input element using document.getElementById('abc').focus(), I am able to see the yellow background.

const input = document.getElementById('abc');

input.focus();
<!DOCTYPE html>
<html>

<head>
  <style>
    input:focus {
      background-color: yellow;
    }
  </style>
</head>

<body>

  <p>Click inside the text fields to see a yellow background:</p>

  <form>
    First name: <input id="abc" type="text" name="firstname"><br>
  </form>

</body>

</html>

Upvotes: 1

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

document.getElementById('abc').focus(); will work if you put this line in <script> in head section of heml.

Or if you want to do it with jQuery then you need to put that code in document.ready function like this:

$(document).ready(function(){
    $('#abc').focus();
});

Upvotes: 0

Related Questions