Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force "enter key" to act as "tab key" using javascript?

I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do. I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on

<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />

<script type="text/javascript">

    function noNumbers(e) {

        keynum = e.which;

        if (keynum == 13)
            document.getElementById("Text2").focus();

    }
</script>

I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript

like image 945
Heba Gomaah Avatar asked May 10 '12 15:05

Heba Gomaah


1 Answers

This will handle multiple input fields.

Here is the jQuery version: http://jsfiddle.net/TnEB5/3/

$('input').keypress(function(e) {
    if (e.which == 13) {
        $(this).next('input').focus();
        e.preventDefault();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text"  />
<input id="Text2" type="text" />
<input id="Text3" type="text" />

Here is the pure javascript version: http://jsfiddle.net/TnEB5/5/ (you probably want to get the sibling differently)

function tab(e) {
    if (e.which == 13) {
        e.target.nextSibling.nextSibling.focus();
        e.preventDefault();
    }
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
    var input = inputs[x];
    input.onkeypress = tab;
}
<input id="Text1" type="text"  />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
like image 117
bygrace Avatar answered Oct 15 '22 10:10

bygrace