Ario
Ario

Reputation: 346

jQuery keyup event not working properly

$(function(){

  $("input.custom").hide();
  $("input.custom").wrap("<div class='customInput'></div>");
  $(".customInput").html("Type");

  $(document).on("keyup", ".customInput", function(event){
    alert(event.keyCode);
  });

});

html

...
<body>
  <input type="text" class="custom" />
</body>
...

i've a code like this and it should give an alert of the keycode if a keyboard button is pressed while .customInput is focused.. but it's not working

Little like THIS
Jsfiddle HERE

Upvotes: 1

Views: 1430

Answers (1)

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11290

Because you don't have an input with class customInput.
Do it like this:

$(document).on("keyup", ".custom", function(event){
    alert(event.keyCode);
});

Or if you want to do bind the event do the div.customInput element:

// Add tabIndex to div - this makes the div selectable and enables keyboard events on it
$("input.custom").wrap("<div class='customInput' tabIndex='1'></div>");

$('.customInput').keyup(function(event){
    alert(event.keyCode);
});

Here is the fiddle for the second option - http://jsfiddle.net/WQL4X/4/
Normally div won't capture key events but if it's selectable it does. To make it selectable you have to provide tabIndex attribute. That's it.

Upvotes: 2

Related Questions