1

Please consider this code:

<input name="TextBox1" type="text" value="1111111111" id="TextBox1" />
<br />
<input name="TextBox2" type="text" value="222222222" id="TextBox2" />
<br />
<input name="TextBox3" type="text" value="3333333333" id="TextBox3" />
<br />
<input name="TextBox4" type="text" value="4444444444" id="TextBox4" />
<br />
<select name="DropDownList1" id="DropDownList1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<br />
<input id="CheckBox1" type="checkbox" name="CheckBox1" />
<label for="CheckBox1">nima</label>
<br />
<input id="Button1" type="button" value="button" />

and javascript:

$(document).ready(function () {
        $("#Button1").click(function () {
            var e = jQuery.Event("keydown");
            e.which = 9; // # Some key code value
            e.keyCode = 9;
            $("#TextBox1").trigger(e);
        });

        $("#TextBox1").on("keydown", function (e) {
            alert(e.keyCode);
        });
    });

the problem is when I press TAB on TextBox1 I get message "9" for keyCode and Textbox2 get focus. but when I press Button1 I get message "9" for keyCode but Textbox2 does not get focus. Where is my mistake? thanks

Live Demo

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
Arian
  • 12,793
  • 66
  • 176
  • 300

1 Answers1

2

The mistake is that you're not actually handling the TAB press yourself, the browser is. Pressing TAB whilst one interactive element has focus will inform the browser that you wish to have focus moved on to the next element in line (based on tabIndex).

Your button here isn't actually pressing the TAB key, it's passing the tab event to the input element.

If you wish to have this action blur the #TextBox1 element and focus the #TextBox2 element, you can make use of jQuery's blur() and focus() functions:

$("#TextBox1").on("keydown", function (e) {
    if (e.which === 9) {
        $(this).blur();
        $('#TextBox2').focus();
    }
});

JSFiddle demo.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Thanks @James. the problem is I want to navigate between my controls using `Enter` key. I used a code for this but that code no longer works on IE 11.please see this topic: http://stackoverflow.com/questions/26438274/replace-keycode-in-ie-11 – Arian Oct 20 '14 at 09:47
  • @Kerezo that's a different question. If you feel my post here has answered the question you've asked here, could you please accept it so that it can be closed? Thanks! – James Donnelly Oct 20 '14 at 09:54