1

I am creating an input box and trying to add an event keydown to that input. If I create the input staticly, I can find it with jquery. However, if I create it in code behind, I cannot find it by jquery.

here is the c# code where I create my input dynamically

result0 += "<div style='float:left;width:130px'>Telephone: </div><div style='float:left;width:200px'><input id='txt_basic_telno" + i + "' class='blue_input' type='text' value='" + dr["MobilePhone"].ToString() + "' style='width:250px' maxlength='11' /></div><div style='clear:both'></div>";

and here is my jquery code which is supposed to trigger when user press a key during the focus is on the input box

$("#txt_basic_telno").keydown(function (event) {
        alert('test');
});

How can I fix this?

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

5 Answers5

1

Try this

$(document).on('keydown',"#txt_basic_telno",function (event) {
        alert('test');
});

Read http://api.jquery.com/on

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
1

You need to use on

$(document).on('keydown',"[id^=txt_basic_telno]", function (event) {
        alert('test');
});

Try not to attach this to document though as it's inefficent. replace document with the nearest static container.

Here's a fiddle to demonstrate

EDIT

Stolen selector from dystroy.......his answers better but I wanted to keep the document comment as it's important

Liam
  • 27,717
  • 28
  • 128
  • 190
1

If your id isn't exactly txt_basic_telno but just starts with txt_basic_telno, as seems to indicate your code, then you might use this :

$(document.body).on('keydown', '[id^=txt_basic_telno]', function(e) {
     alert('click!');
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

you are using two different ids : 'txt_basic_telno" + i + "' and just 'txt_basic_telno'

redmoon7777
  • 4,498
  • 1
  • 24
  • 26
-1

jQuery binds the event handler to any existing objects that match the selector when the jQuery function is called, so if you want it to apply to the dynamically-created content you'll need to call the jQuery .keydown function each time after the new elements are created.

3nafish
  • 256
  • 2
  • 16