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

javascript - How to focus a hidden input field - Stack Overflow

programmeradmin2浏览0评论

I'm new to JS and trying to make an input field that that only appears when the user types anywhere on the page. Currently, the appearing of the input field works but once it's visible, the user still has to click into the field to type in it.

I would like it to work like:

  • User presses "S"
  • Field appears with "S" typed in it.

Any help would be much appreciated!

var searchArea = $(".search");

searchArea.hide();

$(document).ready(function()  {

  $( "body" ).keydown(function() {
    searchArea.show();
    searchArea.elements['input'].focus();
    console.log("worked!");
  });

});

I'm new to JS and trying to make an input field that that only appears when the user types anywhere on the page. Currently, the appearing of the input field works but once it's visible, the user still has to click into the field to type in it.

I would like it to work like:

  • User presses "S"
  • Field appears with "S" typed in it.

Any help would be much appreciated!

http://codepen.io/jeremypbeasley/pen/RNrore

var searchArea = $(".search");

searchArea.hide();

$(document).ready(function()  {

  $( "body" ).keydown(function() {
    searchArea.show();
    searchArea.elements['input'].focus();
    console.log("worked!");
  });

});
Share Improve this question asked Dec 6, 2014 at 14:13 Jeremy P. BeasleyJeremy P. Beasley 7091 gold badge7 silver badges22 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

What is searchArea.elements['input'] supposed to do ?

Try it like this instead, using jQuery's find method

$( "body" ).on('keydown', function() {
    searchArea.show().find('input').focus();
});

PEN

You need to find the input element within the seach area, then call focus() on it:

$(document).ready(function()  {
  var $searchArea = $(".search").hide();

  $("body").keydown(function() {
    $searchArea.show();
    $searchArea.find('input').focus();
  });  
});

Updated CodePen

Or just set id to input field (<input autofocus="autofocus" id="hid_inp" >) and use $("#hid_inp").focus(); instead of searchArea.elements['input'].focus();"

发布评论

评论列表(0)

  1. 暂无评论