focus on next tabindex of HTML element onEnter keypress by JQuery

不羁的心 提交于 2019-11-27 20:14:29

I found a couple of minor jQuery issues. Fixed here: 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').

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.

eapo

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

  1. How to prevent ENTER keypress to submit a web form?
  2. Focus Next Element In Tab Index
<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>
karlisup

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.

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

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.

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

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:

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.

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

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!