8

This simple selector finds the first empty text input field in my form but skips over password type inputs:

$('input:text[value=""]:first').focus();

Is there a neat way to say :text or :password in the above statement?

cneeds
  • 319
  • 3
  • 13

4 Answers4

10
$('input:text[value=""]').add('input:password[value=""]').first().focus();

I don't think there is a better way. That's what I thought before taking a look at @Hari Das answer which has an issue but brings alternative solution to my mind:

$('input:text[value=""],input:password[value=""]').first().focus()

Choose the one which is more readable to you.

ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
  • Ah yes, I was trying to get to your second version but left out the input after the comma. Why does this have an issue? Do you know? – cneeds Apr 23 '14 at 18:18
  • Surprising a little bit. Should work as well but it's recommended to use `input:password` instead of `:password` for better performance. – ElmoVanKielmo Apr 24 '14 at 06:00
4

Here a little custom expression :

$.expr[':'].is = function(a,b,c){
    return $(a).is(c[3])
}

That allow you to use is in a selector. You can achieve what you want with that :

$('input[value=""]:is([type=text],[type=password]):first')

Fiddle

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

By using comma you can insert multiple selector. It works like an OR operator.

$('input:text[value=""]:first,input:password[value=""]:first')
Hari Das
  • 10,145
  • 7
  • 62
  • 59
1

The visible is there to skip any hidden fields, such as select2 autogenerated inputs.

$('input:text[value=""]:visible:first',input:password[value=""]:first)
Adrian P.
  • 5,060
  • 2
  • 46
  • 47
  • password type fileds could also be invisible I guess. Thus `$('input:text[value=""]:visible:first,input:password[value=""]:visible:first')` – cneeds Dec 18 '17 at 15:11