Reputation: 8705
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
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
Reputation: 13471
use :focus selector
index = input.index(input.filter(':focus'))
Upvotes: 3
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
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