14

I have a textbox which I want to set the focus on, but it doesn't work.

document.getElementById("txtCity").focus();

Any idea?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Itay.B
  • 3,991
  • 14
  • 61
  • 96
  • What does the html for the textbox look like? – Larry Hipp Jan 25 '11 at 20:42
  • 6
    Is `document.getElementById("txtCity")` returning `undefined`? Any JavaScript errors in a console? What browser? Is the element actually focusable? **Show more code.** – Matt Ball Jan 25 '11 at 20:43
  • Using IE8. No errors on the page. – Itay.B Jan 25 '11 at 20:44
  • for example Fx will not do a getElementById on – mplungjan Jan 25 '11 at 20:45
  • We need more code, since this basic command clearly works. http://jsfiddle.net/kBxA4/2/ – Dutchie432 Jan 25 '11 at 20:45
  • I see my mistake now. I did something wrong. You are right. It does work. I appreciate your help. – Itay.B Jan 25 '11 at 20:49
  • What was your mistake? Please explain in an answer you write yourself, so we can see and learn. If you don't want to, please delete this entire question, it is of no use to let only a snap of code with an unanswered/unanswerable question linger around. – Marcel Korpel Jan 25 '11 at 21:09

7 Answers7

13

Maybe you are calling the JavaScript before the input element is rendered? Position the input element before the JavaScript or wait until the page is loaded before you trigger your JavaScript.

In that order, it works just fine:

<input type="text" id="test" />
<script type="text/javascript">
  document.getElementById("test").focus();
</script>

In jQuery you could place your code within the .ready() method to execute your code first when the DOM is fully loaded:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
    $("#test").focus();
    // document.getElementById("test").focus();
  });
</script>
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
13

In case someone searching has a similar situation to mine ... I had to set a tabindex attribute before my div could receive focus():

featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true

(I found my answer here: Make div element receive focus )

And of course, make sure the body element is ready before setting focus to a child element.

Symbolic
  • 693
  • 5
  • 10
8

I have also faced same problem.To resolve this problem, put your code in setTimeout function.

function showMeOnClick() {
    // Set text filed focus after some delay
    setTimeout(function() { jQuery('#searchTF').focus() }, 20);
    // Do your work.....
}
Rubi saini
  • 2,515
  • 23
  • 21
  • 5
    Doing this with a timeout is just quick&dirty – d0n.key Jun 10 '17 at 21:30
  • Yes, adding timeout is just a workaround because we need a next tick kind of event to repaint the DOM to show the changes. We can opt another approach to solving this problem :-) – Rubi saini Jun 12 '17 at 04:19
  • I solved it by applying an "animationend" listener for the created object's animation (because my object appears with an animation). This way it gets the focus once it is where it's supposed to be. – d0n.key Jun 12 '17 at 14:35
0

Try to wrap it into document ready function and be sure, that you have jquery included.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script>
       $(document).ready(function() {
          $("#test").focus();
       });
    </script>
kajo
  • 5,631
  • 4
  • 31
  • 29
0

I had a similar problem as Martin Buberl mentioned above, the element did not exist on the moment I gave focus(). I used window.requestAnimationFrame() to give a callback which will give focus on the next render.

window.requestAnimationFrame(() => elm.focus())
Steve Jung
  • 33
  • 4
-1
    <div id="txtROSComments" contenteditable="true" onkeyup="SentenceCase(this, event)"style="border: 1px solid black; height: 200px; width: 200px;">
    </div>
    <script type="text/javascript">
        function SentenceCase(inField, e) {
            debugger;
            var charCode;

            if (e && e.which) {
                charCode = e.which;
            } else if (window.event) {
                e = window.event;
                charCode = e.keyCode;
            }

            if (charCode == 190) {
                format();
            }
        }

        function format() {
            debugger; ;
            var result = document.getElementById('txtROSComments').innerHTML.split(".");

            var finaltxt = "";


            var toformat = result[result.length - 2];

            result[0] = result[0].substring(0, 1).toUpperCase() + result[0].slice(1);

            if (toformat[0] != " ") {

                for (var i = 0; i < result.length - 1; i++) {
                    finaltxt += result[i] + ".";
                }

                document.getElementById('txtROSComments').innerHTML = finaltxt;
                alert(finaltxt);
                abc();
                return finaltxt;
            }



            if (toformat[0].toString() == " ") {
                debugger;
                var upped = toformat.substring(1, 2).toUpperCase();

                var formatted = " " + upped + toformat.slice(2);

                for (var i = 0; i < result.length - 1; i++) {

                    if (i == (result.length - 2)) {
                        finaltxt += formatted + ".";
                    }
                    else {
                        finaltxt += result[i] + ".";
                    }

                }
            }
            else {
                debugger;
                var upped = toformat.substring(0, 1).toUpperCase();

                var formatted = " " + upped + toformat.slice(1);



                for (var i = 0; i < result.length - 1; i++) {
                    if (i == (result.length - 2)) {
                        finaltxt += formatted + ".";
                    }
                    else {
                        //if(i
                        finaltxt += result[i] + ".";
                    }

                }

            }
            debugger;
            document.getElementById('txtROSComments').value = finaltxt;
            return finaltxt;

        }

    </script>
   <script type="text/javascript">
       function abc() {
           document.getElementById("#txtROSComments").focus();
       }

asdf
  • 15
  • 1
-3

It works fine in this example http://jsfiddle.net/lmcculley/rYfvQ/

Lance
  • 1,889
  • 14
  • 12