Tintin81
Tintin81

Reputation: 10207

How to target specific fields in form with jQuery?

I want to target the first input[type="text"] element in a form and if the form does not contain such an element then target the first input[type="number"] element.

How can this be done?

This is what I've got so far:

$('input[type=text]:first, input[type=number]:first').focus();

Thanks for any help.

Upvotes: 1

Views: 127

Answers (5)

Diogo Paschoal
Diogo Paschoal

Reputation: 1667

Man, the behavior of the selectors is like in css, and, in this way, you cannot have a failover selector (if one don't exists, get another). You'll have to use a if like this:

if (!$('form input[type=text]:first').size()){
  $('form input[type=text]:first').focus();
}else{
  $('form input[type=number]:first').focus();
}

You can save the selector result to avoid the dom search again in the focus function with something like:

first_result = $('form :input[type=text]:first')

Upvotes: 1

photodow
photodow

Reputation: 255

The problem with your code is that you are selecting both the first input[type="text"] AND input[type="number"] elements on the page. that's what the , means in your jQuery selector.

What you need to do is check for the input[type="text"]. If it doesn't exist then you use the input[type="number"]. So you're going to need a conditional statement for this.

Solution:

var firstInput;

firstInput = $('input[type="text"]:first-child');

if(firstInput.length > 0){
    console.log(firstInput);
}else{
    firstInput = $('input[type="number"]:first-child');
    console.log(firstInput);
}

Here is the jsfiddle: http://jsfiddle.net/UL6k3/2/

Upvotes: 0

Nico O
Nico O

Reputation: 14102

you may also use :first-of-type.

$('input[type="text"]:first-of-type, input[type="number"]:first-of-type').focus();

Upvotes: 0

j08691
j08691

Reputation: 207901

if ($('input[type=text]:first').length) {
    $('input[type=text]:first').focus();
} else {
    $('input[type=number]:first').focus();
}

jsFiddle example

Upvotes: 2

Ram
Ram

Reputation: 144689

You can use the .first() method.

$('form input').filter('[type=text], [type=number]').first().focus();

http://jsfiddle.net/5aafz/

Upvotes: 4

Related Questions