Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wanted: 'Super selector' or How focus the first visible "input" field that has no value?

I was wondering if it is possible to focus the first empty visible "input" field with only one jQuery selector: something like $('superamazingselector').focus();

With "input" fields I mean: text areas, inputs (not type="hidden"), selects, radio buttons, unchecked checkbox fields. I guess this 'super selector' would be very handy on many pages.

like image 758
Kees C. Bakker Avatar asked Dec 16 '22 18:12

Kees C. Bakker


1 Answers

Try this (untested):

$(':input[value=""]:visible:not(:button):first, :checkbox:not(:checked):first').first().focus();
  • :input - pseudo-class selector for all form input elements (includes <textarea> and <select>)

  • [value=""] - value attribute is empty

  • :visible - filters out hidden elements (doesn't select <input type="hidden" />)

  • :not(:button) - :not() a <button> or <input type="button" />

  • :checkbox - selects checkboxes

  • :not(:checked) - checkboxes that are :not() checked

How you select radio buttons depends on your HTML structure for <input type="radio" />, I can't think of a one-size-fits-all selector that detects an unselected radio button group.

like image 177
BoltClock Avatar answered Mar 16 '23 00:03

BoltClock