最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't set focus() on a text field - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Nov 30, 2010 at 4:51 Phil KulakPhil Kulak 7,2208 gold badges46 silver badges50 bronze badges 1
  • Btw, how do you know what you can do ".then" on the partial? I can't, for the life of me, figure out what the "partial" method returns from Sammy.js api docs. How do you figure that stuff out? – Andriy Drozdyuk Commented Jan 12, 2012 at 17:44
Add a comment  | 

4 Answers 4

Reset to default 14

Try:

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

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

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.

If you are sure that you are getting $('#item') object.You can try out few things.

Make sure that you have only one input box with <input type="text" id="item" />.Same id should not be repeated.

Next thing is why dont you try $('#item').focus().

Thanks. with regards,

Wasim

Do it like this:

i.trigger 'focus'
发布评论

评论列表(0)

  1. 暂无评论