user796443
user796443

Reputation:

How to jquery .focus() element if user types anythign

I've nested ul activated by hover on parent li.

All works except that I've a search form in fly-out menu, I'd like this input field to be focused if user types anything.

I cannot seem to ge this part right, any ideas? How I've implemented now, works only if I already select input and hit some key, this is because $this is input.

   //Flyout menu in big_header
   $(".flyout_big").removeClass("fallback");
   $("#head_big .categories > ul > li").hover(
    function() {
        //$('ul', this).stop().slideDown(100);
        $(".flyout_big", this).stop().fadeIn("fast");
        var offset = $(this).offset();
        $(".flyout_big .flyout_arrow", this).stop().animate({top:offset.top},"slow");

        //Activate-focus search field on any key-press
          $(document).on("keydown",function(e){
              //if (e.keyCode == 13) {  
              //    alert("enter");
              //} else if (e.keyCode == 27) {
              //    alert("esc");
              //}
              //alert("test");
              $(".search_field").focus();
          });

    },
    function() {
        //$('ul', this).stop().slideUp(100);
        $(".flyout_big", this).stop().fadeOut("fast");
    });
   //End floyout menu in big_header

Upvotes: 0

Views: 137

Answers (2)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

Used this code :

$('li *').hide();
$("ul > li").hover(function(){
    var $this = $(this);
    $this.find('*').show();
    $(document).on("keydown",function(){
        $this.children('input').focus();
    });
},
function(){
    var $this = $(this);
    $this.find('*').hide();
});

Fiddle : http://jsfiddle.net/6hEwD/4/

Once the document is on focus and you are hovering the div, you can type into the input.

Upvotes: 0

Rens Tillmann
Rens Tillmann

Reputation: 474

Html:

<ul>
    <li>Test 1<br /><input type="text" /></li>
    <li>Test 2</li>
<ul>

Script:

$(document).ready(function()
{
    $("ul > li").hover(function()
    {
        $("ul > li").removeClass('active');
        $(this).addClass('active');
    });
    $('html').on("keyup",function()
    {
        alert('test');
        $("ul > li").filter(".active").children('input').val('test').focus();
    });
});

jsFiddle (note that you first have to click once on the html box):

http://jsfiddle.net/6hEwD/

Upvotes: 1

Related Questions