user1681166
user1681166

Reputation: 241

change focus to next tab index control jquery when left/right arrow key press

I have radio button

  Are you SSC Passed
 <input tabindex='1'  type='radio' name='categoryName1'   id='radio1' /> 
  <input tabindex='2'  type='radio' name='categoryName1'   id='radio2' /> 

  Are you Holding Passport

 <input tabindex='3'  type='radio' name='categoryName2'   id='radio3' /> 
  <input tabindex='4'  type='radio' name='categoryName2'   id='radio4' /> 

Jquery Code to move to next control when left-rightarrow key press

$(document).on('keydown', 'input,select,textarea,a,button', function (e) {
        if (e.which == 37) {
            var tabIndexKey =  document.activeElement.tabIndex-1;

            $('[tabindex=' + tabIndexKey + ']').focus();

        }
        if (e.which == 39) {
            var tabIndexKey =  document.activeElement.tabIndex+1;
            $('[tabindex=' + tabIndexKey + ']').focus();


        }
    });

But the problem is when i press arrow key focus is not moving to tabindex 3. It move again to 1 or 2.

Upvotes: 0

Views: 1891

Answers (1)

Projesh Pal
Projesh Pal

Reputation: 458

Your code is right but you have two set of radio buttons. 1. SSC Pass 2. Passport Hold

Now either you may switch between two option each [eg: SSC Pass[Y,N], Passport Hold[Y,N] ] or if you want to navigate between Four option you have to name all the radio button same as CategoryName1 or CategoryName2

$(document).on('keydown', 'input,select,textarea,a,button', function (e) {
        if (e.which == 37) {
            var tabIndexKey =  document.activeElement.tabIndex-1;

            $('[tabindex=' + tabIndexKey + ']').focus();

        }
        if (e.which == 39) {
            var tabIndexKey =  document.activeElement.tabIndex+1;
            $('[tabindex=' + tabIndexKey + ']').focus();


        }
    });

$(document).on('keydown', 'input,select,textarea,a,button', function (e) {

        if (e.which == 37) {
            var tabIndexKey =  document.activeElement.tabIndex-1;
            $('[tabindex=' + tabIndexKey + ']').focus();
            alert(e.which+': '+document.activeElement.tabIndex);

        }
        else if (e.which == 39) {
            var tabIndexKey =  document.activeElement.tabIndex+1;
            $('[tabindex=' + tabIndexKey + ']').focus();
            alert(e.which+': '+document.activeElement.tabIndex);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Are you SSC Passed
 <input tabindex='1'  type='radio' name='categoryName1'   id='radio1' /> 
  <input tabindex='2'  type='radio' name='categoryName1'   id='radio2' /> 

  Are you Holding Passport

 <input tabindex='3'  type='radio' name='categoryName2'   id='radio3' /> 
  <input tabindex='4'  type='radio' name='categoryName2'   id='radio4' />

Upvotes: 1

Related Questions