1

I have a page with multiple text inputs, and I want to determine which of the text inputs that the user is typing into. All of the text inputs are displayed with the same code. One big constraint is that I cannot modify the actual HTML code, so I cannot add IDs or classes to the input.

Here is what the HTML looks like:

<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />

Here is the code that I am using to detect a keypress:

$(document).keypress(function(e) {
console.log(e.target) // will be the same for each input
});

Is there a way to distinguish between the different inputs. Is there an underlying DOM property that differentiates the text inputs such that I can access the inputs in constant time in the future(ie, does the DOM assign each input a unique id)?

egidra
  • 8,537
  • 19
  • 62
  • 89
  • 1
    You can use jQuery ui to create a unique id: http://stackoverflow.com/questions/1817114/jquery-create-a-unique-id. `$('input').uniqueId();` – Daniel Gimenez Jul 12 '13 at 00:53
  • What do you need to do with this "id" to identify the element? – epascarello Jul 12 '13 at 01:00
  • I want to be able to capture how the users interacted with a form in the future. – egidra Jul 12 '13 at 01:15
  • Have you tried selecting the element with jQuery .find() .children() and binding events? something like this:http://jsfiddle.net/aLXsp/1/ – Cԃաԃ Jul 12 '13 at 01:26
  • `e.target` returns the same element every time, regardless of which element is focused/active? Really? I'd suggest, perhaps, `document.activeElement`, but I'm really not quite sure what you're trying to do, or what's not working. – David Thomas Jul 12 '13 at 09:16

2 Answers2

1

On document load, you can loop through the input elements and make an "index" => "element" map. This can be used for constant time access in the future. The index of the map can act as the unique ID for the element.

I've put together a working fiddle for this. http://jsfiddle.net/fugHv/6/ . Does this solve your problem?

Here's the gist of the approach,

$(document).ready(function(){
    var inputMap = {}, inputArray = [];

    $.each($('input'), function(i, v){
        //Make an array of the inputs to ensure a constant time access
        inputArray.push(v);
        //Make a map of inputs with index as the key, for future use
        inputMap[i] = v; 
    });

    $('input').keypress(function(e){
        var pos = inputArray.indexOf(e.target);

        //This should provide the reference for the target input
        var inputRef = $(inputMap[pos]);
        ...
    }); 
});
Chetan
  • 56
  • 4
1

You can uniquely identify inputs using jQuery index method :

$(document).keypress(function(e) {
console.log(e.target) // will be the same for each input
console.log($(e.target).index());
}); 
geekonweb
  • 384
  • 4
  • 14