Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

What are some reasons for jquery .focus() not working?

Some thoughts are that the ELEMENT_ID.focus() is inside divs that are hidden at certain times.

This should be an easy problem to solve -- but I'm struggling :(

***code works fine -- the text field isn't being focused on upon page loading up.

STEP1 [SOLVED] JAVASCRIPT:

$("#goal-input").focus();

$('#goal-input').keypress(function(event){
 var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13') {
etc, etc, etc
}

HTML

<input type="text" id="goal-input" name="goal" />

[STEP2] JAVASCRIPT:

 if (goal) {
          step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast');

etc, etc

HTML:

  <div id="step-2">
        <div class="notifications">
        </div>
        <input type="text" id="name"   name="name" placeholder="Name" />
               <script type="text/javascript">
              $(function(){
              $("#name").focus();
              });
            </script>

Why doesn't step 2 work? :(

question from:https://stackoverflow.com/questions/9596419/what-are-some-reasons-for-jquery-focus-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to either put the code below the HTML or load if using the document load event:

<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
    $("#goal-input").focus();
});
</script>

Update:

Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:

if (goal) {
      step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast', function() {  
              $("#name").focus();
          });
      });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...