jQuery Dynamically focus on the first INPUT or Textarea

后端 未结 9 1412
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 04:11

Here\'s a tricky one to start the morning.

I have a series of icons. When you click an icon it loads a form. Some of the forms have input[text] others have textareas

相关标签:
9条回答
  • 2020-12-29 04:29
    $(":input:first").focus(); 
    

    The :input selector grabs all input, textarea, select and button elements.

    0 讨论(0)
  • 2020-12-29 04:32

    Here it is:

    $('#form-id :input:enabled:visible:first').focus();
    

    #form-id is ID of the form; :input selects any input and textarea element; :enabled ensures the input is editable; :viisble ensures that the element is visible; :first is obvious

    0 讨论(0)
  • 2020-12-29 04:40

    EDIT

    This is actually not that great of a solution. Patricia's and Onkelborg's solutions below are much more elegant.

    var $firstInput = jQuery("input:first");
    var $firstTextArea = jQuery("textarea:first");
    
    if(firstInput.length == 0) {
      $firstTextArea.focus();
    }
    
    else {
      $firstInput.focus();
    }
    
    0 讨论(0)
提交回复
热议问题