1

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.

5
  • what happens when you delete the *:'s? Commented Feb 4, 2014 at 17:42
  • Yeah, I don't think you need *: Commented Feb 4, 2014 at 17:44
  • i would get rid of the whole form *: as well, because inputs will always be in forms Commented Feb 4, 2014 at 17:44
  • 1
    this is strange, because you're trying to focus two inputs - how come? Commented Feb 4, 2014 at 17:46
  • Yes, you are right. I might as well get rid of those *. The problem is that the second selector seems to override the first one. Commented Feb 4, 2014 at 17:47

5 Answers 5

4

You can use the .first() method.

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

http://jsfiddle.net/5aafz/

Sign up to request clarification or add additional context in comments.

Comments

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

jsFiddle example

Comments

1

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')

1 Comment

You need to remove the '*:' from the selectors.
0

you may also use :first-of-type.

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.