关注JQuery下一个HTML元素onEnter按键的制表索引

时间:2022-08-23 22:40:12

Hi Friends, I'm working on a small task which is to enable the user to tabindex the html element upon enter keypress.

嗨,朋友们,我正在做一个小任务,就是让用户在输入按键时对html元素进行制表。

As im new to jquery , I have written some code which seems to me that It will work ,but there are some problems in it.

由于我是jquery新手,所以我写了一些代码,在我看来它是可以工作的,但是它有一些问题。

Initial findings
The culprit code ,it doesnt work ,as the ouput in the Msg lablel is "Undefined"

最初的发现罪魁祸首的代码,它不起作用,因为味精标签中的输出是“未定义的”

$('*').attr('tabindex').id

关注JQuery下一个HTML元素onEnter按键的制表索引

The code is given below and I have even created a JSFiddle.

下面给出了代码,我甚至创建了一个JSFiddle。

JQuery

JQuery

 $(document).ready(function (eOuter) {
    $('input').bind('keypress', function (eInner) {
        if (eInner.keyCode == 13) //if its a enter key
        {
            var tabindex = $(this).attr('tabindex');
            tabindex++; //increment tabindex
            //after increment of tabindex ,make the next element focus
            $('*').attr('tabindex', tabindex).focus();

                       **//Msg Label**
            //Just to print some msgs to see everything is working
            $('#Msg').text( this.id + " tabindex: " + tabindex 
               + " next element: " + $('*').attr('tabindex').id);

            return false; // to cancel out Onenter page postback in asp.net
        }
    });
}
);

HTML

HTML

<div>
    Employee Info<br />
    Name<br />
    <input name="TxtbxName" type="text" value="ok" id="TxtbxName" tabindex="1" />
    <br />
    Age<br />
    <input name="TxtbxAge" type="text" id="TxtbxAge" tabindex="2" />
    <br />
    Gender<br />
    <select name="DdlGender" id="DdlGender" tabindex="3">
      <option selected="selected" value="Male">Male</option>
      <option value="Female">Female</option>
    </select>
    <br />
    <div>
        Previous Employment<br />
        <select name="DdlCompany" id="DdlCompany" tabindex="4">
   <option selected="selected" value="0">Folio3</option>
   <option value="1">Null Soft</option>
   <option value="2">Object Soft</option>
   <option value="3">Excepption Soft</option>
    </select>
        &nbsp;&nbsp;or Enter Code&nbsp;&nbsp;
        <input name="TxtbxCompanyCode" type="text" id="TxtbxCompanyCode" tabindex="5" />
        <br />
        Address<br />
        <input name="TxtbxAddress" type="text" id="TxtbxAddress" tabindex="6" />
        <br />
       <input type="submit" name="BtnSubmit" value="Submit" id="BtnSubmit" tabindex="7"/>
        <br />
        <label id="Msg">Message here</label>
    </div>
</div>

Let me know where I went wrong :/

告诉我哪里出错了:/

6 个解决方案

#1


13  

I found a couple of minor jQuery issues. Fixed here: JSFiddle.

我发现了几个jQuery小问题。固定:JSFiddle。

This line:

这条线:

$('*').attr('tabindex', tabindex).focus();

can be written like this:

可以这样写:

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

and this:

这:

$('#Msg').text($(this).id + " tabindex: " + tabindex 
           + " next element: " + $('*').attr('tabindex').id);

is not calling the id attribute the jQuery way (you are using JavaScript syntax, but the result of $(this) is a jQuery object. So... $(this).id becomes $(this).attr('id').

不是以jQuery的方式调用id属性(您使用的是JavaScript语法,但是$(this)的结果是jQuery对象。所以…(美元)。id成为美元(这).attr(id)。

The form still has a submission problem, that I didn't dig too far into, but it changes focus and fills out the '#Msg' element now.

这个表单仍然有一个提交问题,我没有深入研究这个问题,但是它改变了焦点并填充了#Msg元素。

#2


5  

Here is my full working code to focusNextElement on keydown [Enter] without jQuery with JSFiddle example created based on the following * answers:

下面是我为focusNextElement编写的完整工作代码,它使用的是没有jQuery的keydown [Enter],并基于以下*答案创建了JSFiddle示例:

  1. How to prevent ENTER keypress to submit a web form?
  2. 如何防止输入按键提交web表单?
  3. Focus Next Element In Tab Index
  4. 在选项卡索引中关注下一个元素
<script type="text/javascript">

    function focusNextElement() {
      var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
      if (document.activeElement && document.activeElement.form) {
        var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
          function(element) {
            return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
          });
        var index = focussable.indexOf(document.activeElement);
        focussable[index + 1].focus();
      }
    }

    window.addEventListener('keydown', function(e) {
      if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName === 'INPUT' && e.target.type !== 'textarea') {
          e.preventDefault();
          focusNextElement();
          return false;
        }
      }
    }, true);

</script>

#3


4  

Didn't want to make new post and make SPAM with solution I found useful.

不想做新的帖子和垃圾邮件与解决方案我发现有用。

Collected information from other sources (Brian Glaz code nice-one) and made cross-browser version of Focus Next Element In Tab-index using Enter key.

从其他来源收集信息(Brian Glaz code nice-one),使用Enter key在列表索引中创建跨浏览器版本的Focus Next元素。

Tab-indexes are not one after another, but may also contain a space between (1,2,9,11,30,etc.)

表索引不是一个接一个的,但也可能包含一个空格(1、2、9、11、30等)。

var tabindex = 1; //start tabindex || 150 is last tabindex
    $(document).keypress(function(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13') { //onEnter
            tabindex++;
            //while element exist or it's readonly and tabindex not reached max do
            while(($("[TabIndex='"+tabindex+"']").length == 0 || $("[TabIndex='"+tabindex+"']:not([readonly])").length == 0) && tabindex != 150 ){
                tabindex++;
            }
            if(tabindex == 150){ tabindex = 1 } //reseting tabindex if finished
            $("[TabIndex='"+tabindex+"']").focus()
            return false;
        }
    });

    $("input").click(function() { //if changing field manualy with click - reset tabindex 
        var input = $(this);
        tabindex = input.attr("tabindex");
    })

I hope that someone will find it useful. Feel free to edit/comment it.

我希望有人会觉得它有用。请随意编辑/评论。

#4


2  

var tab = $(this).attr("tabindex");
tab++;
$("[tabindex='"+tab+"']").focus();

#5


1  

Seeking for a solution for exactly this problem, I generated a small jquery function to find the next valid tabindex; suppose it's a bit easier to maintenance and maybe a bit faster than a while loop:

为了找到解决这个问题的方法,我生成了一个小jquery函数来查找下一个有效的tabindex;假设它更容易维护,可能比while循环快一点:

function getNextTabindex(currentTabIndex) {
  return $("[tabindex]").index($("[tabindex=" + currentTabIndex + "]")) + 1;
}

Hope this to be helpful to whoever needs it; this is tested and works.

希望这对任何需要它的人都有帮助;这是经过测试和工作的。

Explaning this in short: seek for the element of the current tabindex, find this element in the list of all tabindex elements, get the index of it and increase the index.

简单解释一下:查找当前tabindex的元素,在所有tabindex元素的列表中找到这个元素,获取它的索引并增加索引。

Then, using this function, you may select the next tabindex element that way:

然后,使用这个函数,您可以选择下一个tabindex元素:

$('[tabindex=' + getNextTabindex($(":focus").attr("tabindex")) + ']').focus();

I didn't test the call but suppose it to work.

我没有测试这个电话,但假设它能工作。

#6


0  

var tabindex= $(this).attr("tabindex");
tabindex++;
$("[tabindex='"+tabindex+"']").focus();

sample for Editable cells in table

表中可编辑单元格的示例

    $(document).on('dblclick', 'td', function () {
        console.log('clicked');
        this.contentEditable = 'true';
    });
 $(document).on('keydown', 'td', function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            this.contentEditable = 'false';
            //  $(this).next().focus().dblclick().focus();
            var tabindex = $(this).attr('tabindex');
            tabindex++;
            var next = $('[tabindex=' + tabindex + ']').focus().dblclick();
            if (next.is('td') == false)
                return true;
            var sel, range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(next[0]);
                range.collapse(true);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(next[0]);
                range.collapse(true);
                range.select();
            }

            return false;
        }
    });

Editable cells in dynamic table

动态表中的可编辑单元格

#1


13  

I found a couple of minor jQuery issues. Fixed here: JSFiddle.

我发现了几个jQuery小问题。固定:JSFiddle。

This line:

这条线:

$('*').attr('tabindex', tabindex).focus();

can be written like this:

可以这样写:

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

and this:

这:

$('#Msg').text($(this).id + " tabindex: " + tabindex 
           + " next element: " + $('*').attr('tabindex').id);

is not calling the id attribute the jQuery way (you are using JavaScript syntax, but the result of $(this) is a jQuery object. So... $(this).id becomes $(this).attr('id').

不是以jQuery的方式调用id属性(您使用的是JavaScript语法,但是$(this)的结果是jQuery对象。所以…(美元)。id成为美元(这).attr(id)。

The form still has a submission problem, that I didn't dig too far into, but it changes focus and fills out the '#Msg' element now.

这个表单仍然有一个提交问题,我没有深入研究这个问题,但是它改变了焦点并填充了#Msg元素。

#2


5  

Here is my full working code to focusNextElement on keydown [Enter] without jQuery with JSFiddle example created based on the following * answers:

下面是我为focusNextElement编写的完整工作代码,它使用的是没有jQuery的keydown [Enter],并基于以下*答案创建了JSFiddle示例:

  1. How to prevent ENTER keypress to submit a web form?
  2. 如何防止输入按键提交web表单?
  3. Focus Next Element In Tab Index
  4. 在选项卡索引中关注下一个元素
<script type="text/javascript">

    function focusNextElement() {
      var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
      if (document.activeElement && document.activeElement.form) {
        var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
          function(element) {
            return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
          });
        var index = focussable.indexOf(document.activeElement);
        focussable[index + 1].focus();
      }
    }

    window.addEventListener('keydown', function(e) {
      if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName === 'INPUT' && e.target.type !== 'textarea') {
          e.preventDefault();
          focusNextElement();
          return false;
        }
      }
    }, true);

</script>

#3


4  

Didn't want to make new post and make SPAM with solution I found useful.

不想做新的帖子和垃圾邮件与解决方案我发现有用。

Collected information from other sources (Brian Glaz code nice-one) and made cross-browser version of Focus Next Element In Tab-index using Enter key.

从其他来源收集信息(Brian Glaz code nice-one),使用Enter key在列表索引中创建跨浏览器版本的Focus Next元素。

Tab-indexes are not one after another, but may also contain a space between (1,2,9,11,30,etc.)

表索引不是一个接一个的,但也可能包含一个空格(1、2、9、11、30等)。

var tabindex = 1; //start tabindex || 150 is last tabindex
    $(document).keypress(function(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13') { //onEnter
            tabindex++;
            //while element exist or it's readonly and tabindex not reached max do
            while(($("[TabIndex='"+tabindex+"']").length == 0 || $("[TabIndex='"+tabindex+"']:not([readonly])").length == 0) && tabindex != 150 ){
                tabindex++;
            }
            if(tabindex == 150){ tabindex = 1 } //reseting tabindex if finished
            $("[TabIndex='"+tabindex+"']").focus()
            return false;
        }
    });

    $("input").click(function() { //if changing field manualy with click - reset tabindex 
        var input = $(this);
        tabindex = input.attr("tabindex");
    })

I hope that someone will find it useful. Feel free to edit/comment it.

我希望有人会觉得它有用。请随意编辑/评论。

#4


2  

var tab = $(this).attr("tabindex");
tab++;
$("[tabindex='"+tab+"']").focus();

#5


1  

Seeking for a solution for exactly this problem, I generated a small jquery function to find the next valid tabindex; suppose it's a bit easier to maintenance and maybe a bit faster than a while loop:

为了找到解决这个问题的方法,我生成了一个小jquery函数来查找下一个有效的tabindex;假设它更容易维护,可能比while循环快一点:

function getNextTabindex(currentTabIndex) {
  return $("[tabindex]").index($("[tabindex=" + currentTabIndex + "]")) + 1;
}

Hope this to be helpful to whoever needs it; this is tested and works.

希望这对任何需要它的人都有帮助;这是经过测试和工作的。

Explaning this in short: seek for the element of the current tabindex, find this element in the list of all tabindex elements, get the index of it and increase the index.

简单解释一下:查找当前tabindex的元素,在所有tabindex元素的列表中找到这个元素,获取它的索引并增加索引。

Then, using this function, you may select the next tabindex element that way:

然后,使用这个函数,您可以选择下一个tabindex元素:

$('[tabindex=' + getNextTabindex($(":focus").attr("tabindex")) + ']').focus();

I didn't test the call but suppose it to work.

我没有测试这个电话,但假设它能工作。

#6


0  

var tabindex= $(this).attr("tabindex");
tabindex++;
$("[tabindex='"+tabindex+"']").focus();

sample for Editable cells in table

表中可编辑单元格的示例

    $(document).on('dblclick', 'td', function () {
        console.log('clicked');
        this.contentEditable = 'true';
    });
 $(document).on('keydown', 'td', function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            this.contentEditable = 'false';
            //  $(this).next().focus().dblclick().focus();
            var tabindex = $(this).attr('tabindex');
            tabindex++;
            var next = $('[tabindex=' + tabindex + ']').focus().dblclick();
            if (next.is('td') == false)
                return true;
            var sel, range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(next[0]);
                range.collapse(true);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(next[0]);
                range.collapse(true);
                range.select();
            }

            return false;
        }
    });

Editable cells in dynamic table

动态表中的可编辑单元格