Focus on the element of the first form if it is Text, Password or a drop-down menu.

I need to write some jQuery in order to focus on the first element of the form if it is a text field, password type or drop-down menu.

      var Text = $('#pagebody').find('input:text:visible:first')
      var Pass = $('#pagebody').find('input:password:visible:first')
      var Select = $('#pagebody').find('select:visible:first')

      if(Text)
      {
        Text.focus();
      }
      else if(Pass)
      {
        Pass.focus();
      }
      else
      {
        Select.focus();
      }

I can't get him to focus on anything passed in the first request of the if statement, and I'm not 100% sure why.

I'm just wondering how I can select it to select the first form element, if it is text, password or a drop-down list?

and if there is text and password, how to choose the first one?

+4
source share
2 answers

This should do it:

$("#pagebody").find('input[type=text],input[type=password],select')
              .filter(':visible:first').focus();
+3
source

:

var element= $('#pagebody').find('input:text:visible, input:password:visible, select:visible').first();
if(element){
  element.focus();
}
+1

Source: https://habr.com/ru/post/1547551/


All Articles