admin管理员组

文章数量:1401673

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?

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?

Share Improve this question asked Nov 19, 2012 at 4:52 crazymaocrazymao 291 gold badge3 silver badges7 bronze badges 4
  • Please avoid same id for multiple inputs id is identifier make that to appear only one time in your page you can use class for this purpose – Akhilraj N S Commented Nov 19, 2012 at 4:56
  • I changed the id into class but still doesn't work – crazymao Commented Nov 19, 2012 at 4:57
  • If not necessary then change the id of the text box make it unique – vivek salve Commented Nov 19, 2012 at 4:58
  • possible duplicate of jquery select divs with same id – Peter Brown Commented Dec 2, 2012 at 18:56
Add a ment  | 

3 Answers 3

Reset to default 5

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

Live Demo

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


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

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

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() {
  $('.monclass').keypress(function(event){
    alert("keycode: " + event.keyCode);
    alert("id: " + this.id);
  });​
});

本文标签: javascriptJquery detect keypress in multiple inputs with same idStack Overflow