Focusing on a button instead of an input field

I have an input field and a close button. When the page loads, it focuses on the input text field (in ready

), but the same focus command $("#param_pattern_value").focus();

in another function (when clicked on tab

) focuses on the close button in the input text field instead.

HTML:

<div tabindex="-1" class="layout-column layout-gt-xs-row layout-align-start-center layout-margin">
<div tabindex="-1" class="classic-text-input mdl-textfield mdl-js-textfield mdl-textfield--floating-label flex">
    <input tabindex="0" class="mdl-textfield__input" type="text" id="param_pattern_value"  value="enter text">
    <label class="mdl-textfield__label" for="param_pattern_value">
        <span>enter 1</span>
    </label>  

    <button tabindex="0" class="mdl-button mdl-js-button  mdl-button--icon mdl-button--accent margin-left clear_icon_in_input">
        <i class="material-icons mdl-textfield__label__icon">close</i>
    </button>

</div>
</div>

      

JS:

$(document).ready(function () {  
     $('#param_pattern_value').focus()
});

$("body").keydown(function(e){
        var TAB     = 9;
        var key = e.which;

        if (key == TAB ){
                    $("#param_pattern_value").focus();
        }
    });

      

LINK TO JSFIDDLE

I tried many options, but always after clicking on tab

it focused on the close button.

Note that on my site the close button is an "X" that is placed inside the input field (the code looks the same).

Am I doing something wrong?

Thank!
Mike

+3


source to share


1 answer


If you want to set focus to the input field #param_pattern_value

whenever a key appears TAB, you can add : .preventDefault()

$("body").keydown(function(e){
    var TAB = 9;
    var key = e.which;

    if (key == TAB ){
       e.preventDefault();
       $("#param_pattern_value").focus();
    }
});

      

Note, that $("#param_pattern_value").focus()

does work in your code keydown

, but your handler runs just before the keydown

default handler . You can simply test this using instead keyup

, or checking the output in the console .



JSFiddle Demo


If you just don't want the button to Xbe focused, set the tabindex="-1"

attribute on the button.

+2


source







All Articles