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).
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).
Share Improve this question asked Jun 4, 2012 at 13:04 SashaSasha 8,70524 gold badges98 silver badges181 bronze badges 1- If you are looking for any input, either select, checkbox, or radios use the ':input' selector. See my answer. – iambriansreed Commented Jun 4, 2012 at 13:16
5 Answers
Reset to default 3use :focus selector
index = input.index(input.filter(':focus'))
http://jsfiddle/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"/>
Use :focus
selector:
index = forma.find(":focus").index();
$.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.
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./cssref/sel_focus.asp
NOT TESTED