Zumwalt
Zumwalt

Reputation: 151

Tab into an input within a hidden element

I'm working on a scenario in which the user would tab into an input within a hidden element. When that input is focused, I want it's parent, the hidden element, to show using jQuery. So far, I can't seem to get this to work.

This is what my HTML looks like:

<div class="select">
<input tabindex="1" type="text" name="search" class="address" id="address-1" placeholder="Tab to the next input.">
<div class="dropdown">
    <div class="dropdown-search">
        <input tabindex="2" type="text" name="search" class="search" id="dropdown-search-1" placeholder="Type to search...">
    </div>            
</div>

and the jQuery:

$('.select').each(function() {
    var dropdown = $('.dropdown', this),
        search = $('.search', this);

    search.focus(function() {
        dropdown.show();
    });
});​

I've also put my code here: http://jsfiddle.net/ae26u/1/

Upvotes: 3

Views: 6175

Answers (2)

Pez Cuckow
Pez Cuckow

Reputation: 14422

A trick to get around this would be to have the element hidden off screen, rather than actually hidden from the DOM.

If it's hidden off screen it's still "drawn" so you could tab into it, and then on tab move it back onto screen.

jQuery:

$('.select').each(function() {
    var dropdown = $('.dropdown', this),
        search = $('.address', this);

    dropdown.focus(function() {
        console.log('show');
        dropdown.css( "left", "0px" )
    });
});​

Html:

<div class="select">
    <input tabindex="1" type="text" name="search" class="address" id="address-1" placeholder="Tab to the next input."><br />
    <input tabindex="2" type="text" name="search" class="dropdown" id="dropdown-search-1" placeholder="Type to search...">
</div> 

jsFiddle example: http://jsfiddle.net/ae26u/7/

Upvotes: 5

Magus
Magus

Reputation: 15124

You can't focus a hidden element with the tab key. But you can use javascript to trigger that.

Example :

$('.select .address').keydown(function(event) {
    // 9 == tab key code
    if (event.keyCode == 9) { 
        // Find the dropdown ...
        var dropdown = $(this).parent().find('.dropdown');

        // ... and show it
        dropdown.show();

        // Focus the input in the dropdown
        dropdown.find('.search').focus();

        return false;
    }
})

With this code, when you hit tab on the visible input, we show the hidden input and we focus it.

Upvotes: 1

Related Questions