Rob
Rob

Reputation: 1216

get index of input element in javascript

If I have 3 input boxes on a web page and the user clicks the second input, I need to get the input index, the position of the input on the page. I need it in pure javascript. This is what I have so far but it doesn't work...

 document.querySelector('html').onclick = function (e) {
    log(e);
}

function log(obj) {
    var nodeName = obj.target.nodeName
    var idx = nodeName.length
    console.log(nodeName, idx);
}

Any help would be appreciated!

Upvotes: 2

Views: 10924

Answers (2)

DaveHolt
DaveHolt

Reputation: 129

Inline:

<input onclick="for(i=0;i<this.parentNode.getElementsByTagName('input').length;i++){if(this==this.parentNode.getElementsByTagName('input')[i]){alert(i);}}">

Or change that to

onclick="show_index(this)"

And Add:

function show_index(which) {
for(i=0;i<which.parentNode.getElementsByTagName('input').length;i++){
if(which==which.parentNode.getElementsByTagName('input')[i]){
alert(i);
}}

Upvotes: 0

vsync
vsync

Reputation: 130491

Pure javascript:

function getIndexFromSet(set, elm){
    var setArr = [].slice.call(set);
    for( var i in setArr )
       if( setArr[i] == elm )
         return i;      
}

The above function can be used like so:

function checkInputFocus(e){
  if(e.target && e.target.nodeName == 'input' )
    index = getIndexFromSet(inputs, e.target);
}

var inputs = document.querySelectorAll('input');
document.addEventListener("click", checkInputFocus);

using jQuery, if you run this on this page (in your console)

var inputs = $('input'); // get all input elements on the page
inputs.index( $('#save-pinned-sites-btn') ); // find the index of spesific one

you will get a number representing the index of an $('#save-pinned-sites-btn') element

Upvotes: 3

Related Questions