1

I have the following jQuery line:

$('#newStep2 input#name').focus().css('background','Red');

Where I am trying to set the focus of a textbox (#name). I am only setting the background to debug to make sure it works.

Well, the background turns red, but the input is not receiving the focus. Um?

EDIT

HTML, per request:

 <fieldset id="newStep2">
    <h3>2. Name It</h3>            
    <label class="scrollTo">Name:</label>
    <input type="text" name="campaign.name" id="name" />
    <p class="step"><a href="javascript:" class="but_next_step">
         Update and Continue</a></p>
 </fieldset>
1
  • maybe another element is taking focus? or maybe there is already a focus listener on your text inputs?
    – Colin
    Oct 6, 2009 at 0:32

1 Answer 1

1

from the jquery docs for focus():

This causes all of the functions that have been bound to the focus event to be executed. Note that this does not execute the focus method of the underlying elements.

To call the focus method, either use the each() method to invoke the focus method on each matched element, or use get(index) to get the nth matched element and call the focus method. So either:

$('#newStep2 input#name').each(function() { this.focus();});

or

$('#newStep2 input#name').get(0).focus();
2
  • 2
    assuming this is in a dom ready block, wouldn't what he has work?
    – Colin
    Oct 5, 2009 at 23:32
  • Colin: Good point. Yeah, it should. I have an app that uses such a method in the ready event handler -- $('form:first :input:first').focus(). Frankly, I don't think it should matter. Just wanted to go with what the docs say.
    – spot
    Oct 5, 2009 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.