Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set focus() on a text field

This is just the weirdest thing. I've got a Sammy.js app, and I want to set focus on a text field right after the HTML loads. I've got this CoffeeScript here:

this.partial('templates/my-template.jqt').then ->
  i = $('#item')
  debugger
  i.focus()

While I'm in the debugger, right on that line, I can inspect "i" and see that it's a JQuery object. I can even call i.val("HI THERE!") and see my text field update. But, calling i.focus() does absolutely nothing. Is there some security feature I'm missing that doesn't let you focus on a text element that was dynamically loaded?

like image 869
Phil Kulak Avatar asked Nov 30 '10 04:11

Phil Kulak


People also ask

How do I set the focus of a field or control?

You can use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object. To read some of the properties of a control, you need to ensure that the control has the focus. For example, a text box must have the focus before you can read its Text property.

How do I give focus to a textfield in Java?

Now that you have a FocusNode , pass it to a specific TextField in the build () method. 3. Give focus to the TextField when a button is tapped Finally, focus the text field when the user taps a floating action button. Use the requestFocus () method to perform this task.

How do I set the focus of a textbox variable?

expression A variable that represents a TextBox object. You can use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object. To read some of the properties of a control, you need to ensure that the control has the focus.

How do you pass a focus node to a text field?

Pass the FocusNode to a TextField Now that you have a FocusNode , pass it to a specific TextField in the build () method. 3. Give focus to the TextField when a button is tapped Finally, focus the text field when the user taps a floating action button.


2 Answers

Try:

setTimeout(function() { $('#item').focus() }, 1);

It's quite common issue. For some reason delaying the focus for 1ms makes it working.

like image 104
kazy Avatar answered Oct 26 '22 15:10

kazy


JQuery's focus() doesn't focus on an element, it binds an event handler to focus. http://api.jquery.com/focus/

Try i.get().focus() instead.

like image 1
Gaurav Avatar answered Oct 26 '22 13:10

Gaurav