Welcome Guest, Not a member yet? Register   Sign In
Smarter forms in regards to ENTER key
#4

what about this version
Code:
(() => {
  'use strict';

  let cancelButtonId = null;
  let theForm = null;
  const ourInputs = [];

  const focusNext = () => {
    const currentField = document.activeElement;
    let currentInputIndex = ourInputs.indexOf(currentField);
    currentInputIndex = (currentInputIndex + 1) % ourInputs.length;
    const input = ourInputs[currentInputIndex];
    input.focus();
  };

  const documentKeyDown = (e) => {
    if (e.defaultPrevented) {
      return;
    }
    if (e.key === 'Enter') {
      if (e.metaKey || e.ctrlKey) {
        if (e.target.form === theForm) {
          e.preventDefault();
          theForm.submit();
        }
      } else if (e.target.nodeName && e.target.nodeName.toLowerCase() !== 'textarea') {
        e.preventDefault();
        focusNext();
      }
    }
  };

  const documentKeyUp = (e) => {
    if (e.defaultPrevented) {
      return;
    }
    if (e.key === 'Escape') {
      e.preventDefault();
      alert('Cancel');
    }
  };

  const documentEditSetup = () => {
    const initialField = document.getElementById('the-field-you-want-to-focus-auto');
    if (initialField) {
      initialField.focus();
    }
    theForm = document.getElementById('the-id-of-the-form');
    const formInputs = Array.from(theForm.elements);
   
    for (const fi of formInputs) {
      const fiType = fi.type.toLowerCase();
      if (!fi.hidden && fiType !== 'hidden' && fiType !== 'submit') {
        ourInputs.push(fi);
      }
    }
   
    cancelButtonId = document.getElementById('cancel-button');
    window.addEventListener('keydown', documentKeyDown);
    window.addEventListener('keyup', documentKeyUp, true);
  };

  if (document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll)) {
    documentEditSetup();
  } else {
    document.addEventListener('DOMContentLoaded', documentEditSetup);
  }
})();
Learning Codeigniter 
Reply


Messages In This Thread
Smarter forms in regards to ENTER key - by joho - 09-20-2023, 01:07 AM
RE: Smarter forms in regards to ENTER key - by SubrataJ - 09-20-2023, 04:02 AM



Theme © iAndrew 2016 - Forum software by © MyBB