Reputation: 12585
I have an html text box with some having class names as numbers
<input type="text" name="msg_timeout" class="numbers" />
similarly there are different text box with class as numbers.I want to assign keydown event to those text box that has class as number so i tried with following ,but not working
$('input.numbers').each
$('.numbers').each
$('input.numbers:text').each
$('input:text.numbers').each
$('input[type=text]').each // only this is working but it selects all textboxes.
kindly let me know idea. CODE BELOW
$(document).ready(function() {
$('input.numbers').each(function() {
$(this).get(0).oncontextmenu = function() { return false; };
$(this).bind("keydown",function(event) {
// alert(window.event);
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8
&& (event.keyCode >=96 && event.keyCode <=105) )
{
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 || event.shiftKey || event.ctrlKey || event.altKey ) {
event.preventDefault();
}
}
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey;
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
//alert('You are prompted to type this twice for a reason!');
return false;
}
}
}
return true;
});
});
});
Upvotes: 3
Views: 1075
Reputation: 8407
you mean "numbers" not as text but as a number, a digit, integer?
$("input").filter(function() {
return $(this).attr("class").match(/\d+/);
});
Upvotes: 0
Reputation: 23094
You haven't posted your entire code, but I'm guessing you might also be adding some elements on the fly?
In that case.. use..
$("input.numbers").live('keydown', function() {
// do stuff here
});
Upvotes: 1
Reputation: 14135
Are you calling the selectors after dom.ready?
$(document).ready(function() {
$('input.numbers').keydown(function() {
// code here
});
});
without the $(document).ready()
it's unpredictable which elements will be present on the screen when your selector is evaluated.
Upvotes: 3
Reputation: 342765
You don't need to explicitly iterate over all matching elements to assign event handlers to them. The following will do the trick:
// bind a keydown handler to all input elements with class 'numbers'
$("input.numbers").keydown(function() {
// handler implementation here
});
Upvotes: 1