0

I was asked to develop a web page without a mouse. The keyboard cursor must be in the input area(example: <input id="input-label" type="text">) immediately when the page is changed.

I tried,

document.querySelector("#input-area").focus();

and

document.querySelector("#input-area").select();

It works with buttons, but does not work in DOMContentLoaded.

document.addEventListener("DOMContentLoaded", function(){
  document.querySelector("#input-area").select();
});

How can I solve it?

Centell
  • 389
  • 3
  • 18

2 Answers2

1

try this, call it when dom is ready

$(document).ready(function () {
    $("#input-area").focus();
});

OR

 <input id="input-area" autofocus="autofocus" />

OR

$(function() {
  $("#input-area").focus();
});
Saurin Vala
  • 1,898
  • 1
  • 17
  • 23
  • 1
    Whats the error in console ... did you include jquery ? @Centell – anees Jun 12 '18 at 06:01
  • yep, jquery included. I tried .ready either. and no errors appear.. I can't understand why id doesn't work. but the `autofocus` works well. It only need `` – Centell Jun 12 '18 at 06:06
1

Try this code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script>


<script>
$(document).ready(function(){
    $('#myAnchor').click(function() {
        $('#mustfocus').focus();
    });

});
</script>

</head>
<body>
<input type="button" id="myAnchor" value="Get focus">
<input type="text" id="mustfocus"/>


</body>
</html>

How about this one which triggers only during DOM is ready:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script>


<script>
$(document).ready(function(){
        $('#mustfocus').focus();
});
</script>

</head>
<body>
<input type="button" id="myAnchor" value="Get focus">
<input type="text" id="mustfocus"/>


</body>
</html>
davinceleecode
  • 777
  • 3
  • 10
  • 31