简体   繁体   中英

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?

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);
 });​

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM