最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Switch between two textareas only when pressing Tab button - Stack Overflow

programmeradmin1浏览0评论

Normally when a user is visiting a web page and pressing TAB button on a keyboard, the selection moves from one element to another starting from the begining of the page.

I am looking for a solution to switch between two particular text areas by pressing TAB button on a keyboard with an initial focus on the first one when web page is loaded? All other elements on the page have to be ignored for this TAB key press event.

How can I achive this?

Thanx for your help!

= Update =

I have managed to make it work under Firefox 12.0 . IE and Chrome do not work properly. Asuming the text area IDs are #ICCID and #MSISDN, the Jquery looks like this:

<script src=".7.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $(document).ready(function() {
            $("#ICCID").focus();
            });

            var $inp = $('.cls');

            $inp.bind('keydown', function(e) {
                var key = e.which;
                if (key == 9) {

                    e.preventDefault();
                    var nxtIdx = $inp.index(this) + 1;                  
                    $(".cls:eq(" + nxtIdx + ")").focus();

                //Simulate Enter after TAB
                var textInput = $("#MSISDN").val();
                var lines = textInput .split(/\r|\r\n|\n/);
                if (lines > 1) {

                    $("#MSISDN").on("keypress", function(e) {
                    if (e.keyCode == 9) {
                    var input = $(this);
                    var inputVal = input.val();
                    setTimeout(function() {
                    input.val(inputVal.substring(0,inputVal.length) + "\n");
                          }, 1);
                       }
                    });
                }



                }
                if (key == 9) {

                    e.preventDefault();
                    var nxtIdx = $inp.index(this) - 1;
                    $(".cls:eq(" + nxtIdx + ")").focus();

                //Simulate Enter after TAB
                $("#ICCID").on("keypress", function(e) {
                if (e.keyCode == 9) {
                var input = $(this);
                var inputVal = input.val();
                setTimeout(function() {
                input.val(inputVal.substring(0,inputVal.length) + "\n");
                      }, 1);
                   }
                });


                }
            });
        });
</script>

Normally when a user is visiting a web page and pressing TAB button on a keyboard, the selection moves from one element to another starting from the begining of the page.

I am looking for a solution to switch between two particular text areas by pressing TAB button on a keyboard with an initial focus on the first one when web page is loaded? All other elements on the page have to be ignored for this TAB key press event.

How can I achive this?

Thanx for your help!

= Update =

I have managed to make it work under Firefox 12.0 . IE and Chrome do not work properly. Asuming the text area IDs are #ICCID and #MSISDN, the Jquery looks like this:

<script src="https://ajax.googleapis./ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $(document).ready(function() {
            $("#ICCID").focus();
            });

            var $inp = $('.cls');

            $inp.bind('keydown', function(e) {
                var key = e.which;
                if (key == 9) {

                    e.preventDefault();
                    var nxtIdx = $inp.index(this) + 1;                  
                    $(".cls:eq(" + nxtIdx + ")").focus();

                //Simulate Enter after TAB
                var textInput = $("#MSISDN").val();
                var lines = textInput .split(/\r|\r\n|\n/);
                if (lines > 1) {

                    $("#MSISDN").on("keypress", function(e) {
                    if (e.keyCode == 9) {
                    var input = $(this);
                    var inputVal = input.val();
                    setTimeout(function() {
                    input.val(inputVal.substring(0,inputVal.length) + "\n");
                          }, 1);
                       }
                    });
                }



                }
                if (key == 9) {

                    e.preventDefault();
                    var nxtIdx = $inp.index(this) - 1;
                    $(".cls:eq(" + nxtIdx + ")").focus();

                //Simulate Enter after TAB
                $("#ICCID").on("keypress", function(e) {
                if (e.keyCode == 9) {
                var input = $(this);
                var inputVal = input.val();
                setTimeout(function() {
                input.val(inputVal.substring(0,inputVal.length) + "\n");
                      }, 1);
                   }
                });


                }
            });
        });
</script>
Share Improve this question edited May 17, 2012 at 14:18 Deniss Baronov asked May 9, 2012 at 12:12 Deniss BaronovDeniss Baronov 1221 silver badge9 bronze badges 5
  • 4 Don't! Please! There are people who need to be able to focus the other elements in the page using tab! Not everybody is capable of using a mouse. – Quentin Commented May 9, 2012 at 12:14
  • @Quentin. Or wants to you the mouse (like I am...) – gdoron Commented May 9, 2012 at 12:15
  • just define two sequential tabindex attributes for textarea but avoid to disable focus for every other element – Fabrizio Calderan Commented May 9, 2012 at 12:16
  • This page is the data entry page, bar code scanner will be used to scan numbers into those fields – Deniss Baronov Commented May 9, 2012 at 12:19
  • Do you mean to say that this behaviour should only occur when the user clicks on the textarea and not when he es naturally to the textarea while tabbing? – LoneWOLFs Commented May 10, 2012 at 6:09
Add a ment  | 

4 Answers 4

Reset to default 2

Catch the keydown action using jQuery, determine which textarea has focus, and then use the focus() method to set the focus to the other textarea.

Supposing that your textareas have id="textarea1" and id="textarea2". First you can set focus to the first textarea when the page loads by doing : $('#textarea1').focus();

$("body").keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    switch(code)
    {
        case 9:
            if($("#textarea1").focus()){
                //First one has focus, change to second one
                $("#textarea2").focus();
            }
            else if($("#textarea2").focus()) {
                //Second one has focus, change to first one
                $("#textarea1").focus();
            }

    }
});

Ok I have found the solution for for my task! It also includes the simulation of ENTER key just after the TAB key event, so user do not need to hit ENTER to go to the new line. Tested with IE9, FF12, Chrome 18.0.x

Here it is:

<script src="https://ajax.googleapis./ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<!-- Switching between ICCIDs and MSISDNs textareas + simulating ENTER key pressing after the TAB key event - START -->
    <script type="text/javascript">
            $(function() {
                $(document).ready(function() {
                $("#ICCID").focus();
                });

                var $inp = $('.cls');

                $inp.bind('keydown', function(e) {
                    var key = e.which;
                    if (key == 9) {

                        e.preventDefault();
                        var nxtIdx = $inp.index(this) + 1;                  
                        $(".cls:eq(" + nxtIdx + ")").focus();

                    //Simulate Enter after TAB
                    var textInput = $("#MSISDN").val();
                    var lines = textInput .split(/\r|\r\n|\n/);
                    if (lines > 1) {

                        $("#MSISDN").on("keyup", function(e) {
                        if (e.keyCode == 9 || e.which  == 9) {
                        var input = $(this);
                        var inputVal = input.val();
                        setTimeout(function() {
                        input.val(inputVal.substring(0,inputVal.length) + "\r\n");
                              }, 1);
                           }
                        });
                    }



                    }
                    if (key == 9) {

                        e.preventDefault();
                        var nxtIdx = $inp.index(this) - 1;
                        $(".cls:eq(" + nxtIdx + ")").focus();

                    //Simulate Enter after TAB
                    $("#ICCID").on("keyup", function(e) {
                    if (e.keyCode == 9 || e.which  == 9) {
                    var input = $(this);
                    var inputVal = input.val();
                    setTimeout(function() {
                    input.val(inputVal.substring(0,inputVal.length) + "\r\n");
                          }, 1);
                       }
                    });


                    }
                });
            });
    </script>
    <!-- Switching between ICCIDs and MSISDNs textareas + simulating ENTER key pressing after the TAB key event -  END -->

What about this.... Im to bored at work i think..

http://jsbin./uqalej/3/

HTML:

<input/>
<textarea id="t1"></textarea>
<textarea id="t2"></textarea>
<input/>

<button onClick='window.toggleBetween=true;'>Init</button>
<button onClick='window.toggleBetween=false;'>Destroy</button>

JS:

var d = document,
    t1 = d.getElementById("t1"),
    t2 = d.getElementById("t2"),

    nodeType, nodeTypes = [],
    i, iLen,
    y, yLen;

nodeTypes.push( d.getElementsByTagName("textarea") );
nodeTypes.push( d.getElementsByTagName("input") );
nodeTypes.push( d.getElementsByTagName("select") );

i = 0;
iLen = nodeTypes.length;
for ( ; i < iLen; i++ ) {
  nodeType = nodeTypes[i];
  y = 0;
  yLen = nodeType.length;
  for ( ; y < yLen; y++ ) {
    if ( nodeType[y] != t1 && nodeType[y] != t2 ) {
      nodeType[y].onfocus = function() {
        if ( window.toggleBetween )
          t1.focus();
      };
    }
  }
}

Using javascript on page load:

document.getElementById("textarea1").focus();
document.getElementById('textarea1').tabIndex="1";
document.getElementById('textarea2').tabIndex="2";
发布评论

评论列表(0)

  1. 暂无评论