Reputation: 4469
For an input field I have used a class
Here code for input field:
<?php
echo $this->Form->input('duration', array('class'=>'input-large text-right number- field','value'=>'0'));
echo $this->Form->error('duration');
?>
Here the jquery class code:
$(".number-field").keypress(function(e) {
var code = e.which || e.keyCode;
if(code >= 48 && code <= 57) {
console.debug(code);
} else {
return false;
}
});
Main reason In input field use can't type character in digits field. This class working fine.But after type digits backspace not working. For example suppose I have typed 1956
, now I want to edit it 1955
. In here I am enable to cut 6
by backspace.
Upvotes: 0
Views: 528
Reputation: 3965
You can use regex for this:
var reg = /^\d+$/; // only number
$(".number-field").keypress(function(e) {
var code = e.which || e.keyCode;
if(reg.test(String.fromCharCode(code))) {
console.debug(code);
} else {
return false;
}
});
Upvotes: 0
Reputation: 2681
You can use following script -
$(".number-field").keypress(function(e) {
var code = e.which || e.keyCode;
//allow Backspace and Delete key.
if((code >= 48 && code <= 57) || code == 8 || code == 46) {
console.debug(code);
} else {
return false;
}
});
Similar to escaping the 'backspace' key you might want to escape the 'Delete' key(code == 46)
If you just want to allow the numbers in input type then you can use HTML5 input type number.
<input type="number" name="year">
Upvotes: 2