Sasha
Sasha

Reputation: 8705

JQuery find index of focused input

How can I find index of a focused input field? For now I have this code:

var forma = $('form#mali_oglas'),
    pomoc = $('div[role=pomoc]'),    
    input = forma.find('input[type!=hidden], textarea');

    index = input.focus().index();
    console.log(index);

All that I get is number of input elements in the form (15 at the moment).

Upvotes: 1

Views: 7927

Answers (5)

iambriansreed
iambriansreed

Reputation: 22261

http://jsfiddle.net/iambriansreed/QyUHv/

jQuery

var f = $('form');
f.click(function(){    
    $('#index').val($(':input:focus',f).index());    
});​

HTML

<form>    
<input value="hello"/><br/>
<textarea></textarea><br/>
<input/><br/>
<input/><br/>
<select><option>Option</option></select><br/>
<input/><br/>
</form><br/><br/>
Field Index with focus:
<input id="index"/>

Upvotes: 2

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13471

use :focus selector

index = input.index(input.filter(':focus'))

Upvotes: 3

Josh Siok
Josh Siok

Reputation: 936

You should be able to use the pseudo class to find the element that has focus.

input = forma.find('input:focus, textarea:focus');

http://www.w3schools.com/cssref/sel_focus.asp

NOT TESTED

Upvotes: 0

Mattias Buelens
Mattias Buelens

Reputation: 20179

$.focus() gives the selected element focus. Instead, you want to select the focused element. Luckily, jQuery's got you covered with :focus.

var input = forma.find('input:focus, textarea:focus');
var index = input.index();
console.log(index);

Note: I removed the [type!=hidden] selector, as hidden input fields can never have focus.

Upvotes: 1

VisioN
VisioN

Reputation: 145458

Use :focus selector:

index = forma.find(":focus").index();

Upvotes: 1

Related Questions