crazymao
crazymao

Reputation: 29

Jquery detect keypress in multiple inputs with same id

So I have a bunch of input boxes with the same id but different names like so:

<input type="text" id="description" name="1">
<input type="text" id="description" name="2">
<input type="text" id="description" name="3">

Now for a single input box (only one box uses the id) I use:

$('#description').keypress(function(....

What I would ideally like to be able to do is use the above function and then do something based on the name of the input box but for multiple input boxes to carry the same id. Is this possible in some way?

Upvotes: 1

Views: 9215

Answers (3)

Tom
Tom

Reputation: 300

It is a little bit late for my answer, but in case someone else stumbles upon this question here.

For me the problem was solved by wrapping the code in the document ready event. This ensures the input controls exist in the DOM at the time the events are attached.

$(document).ready(function() {
  $('.commonclass').keypress(function(event){
    alert("keycode: " + event.keyCode);
    alert("id: " + this.id);
  });​
});

Upvotes: 0

Hemal
Hemal

Reputation: 3760

Apply class name to multiple elements. Then use jquery with class to handle keypress event.

Upvotes: 0

Adil
Adil

Reputation: 148120

You should have unique id for html elements you should assign a common class and access throug it.

Live Demo

<input type="text" id="description1" name="1" class="commonclass">
<input type="text" id="description2" name="2" class="commonclass">
<input type="text" id="description3" name="3" class="commonclass">


 $('.commonclass').keypress(function(event){
       alert("keycode: " + event.keyCode);
       alert("id: " + this.id);
 });​

Upvotes: 5

Related Questions