简体   繁体   中英

can somebody explain the meaning of following code

function handleEnter(event) {
      if (event.key==="Enter") {
          const form = document.getElementById('form')
          const index = [...form].indexOf(event.target);
          form.elements[index + 1].focus();
        }
    }

This code is use for focusing on next input field after pressing Enter somebody explain me this code line by line? it will be big help

Line 1:

const form = document.getElementById('form')

Get the DOM element from html


Line 2:

const index = [...form].indexOf(event.target);

Find in the form elements the index of the current element. I think this line is not correct, I suppose that you want to get child elements from the form element, if so, it should be something like:

const index = form.children.indexOf(event.target);

Line 3:

form.elements[index + 1].focus();

The next element should be the current index plus 1, so just run focus on next element, but as I said, I think that your line 2 is not correct so this line should be something like:

form.children[index + 1].focus();

As I understand. 2nd line: This funct will perform only when press Enter key 3rd line: get information from the form input ("form" ID) 4th line: get the index of the form input 5th line: move the focus point to the next element (which is index+1)

Bro, understanding this code is quite easy you just need to break it down. Let's start with it:-

  • First it is JavaScript function in which html event is passed as argument.
  • Second checks whether the event that is triggered is enter key event
  • If yes, then the next statement will be executed that will select element with form as id.
  • Now from the all the input fields of form current input field will be selected.
  • At last, the index of element that is focus is increment that will shift the focus to next input field in the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM