I have an input field and a close button.
When page loads it focus on the input text field (in ready) but the same focus command $("#param_pattern_value").focus(); in other function (when clicking on tab) focus on the close button instead on the text input field.
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 have tried many variations but always after clicking on tab it focused on the close button.
Note that on my site, the close button is an "X" icon which placed inside the input field (code looks the same).
Am I doing something wrong?
Thanks!
Mike
If you want to set focus on the #param_pattern_value input field whenever a TAB key occurs, you could add a .preventDefault():
$("body").keydown(function(e){
var TAB = 9;
var key = e.which;
if (key == TAB ){
e.preventDefault();
$("#param_pattern_value").focus();
}
});
Please notice, that the $("#param_pattern_value").focus() actually does work in your keydown code, but your handler fires just before the default keydown handler.
You can simply test that using keyup instead, or checking output in console.
JSFiddle Demo
If you simply don't want the X button to be focused, set tabindex="-1" attribute on the button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With