I have a Javascript function that listens to a change event of a TextBox
in a table. The rows have cells with td
class="cost"
type="number"
.
But this is allowing hyphens, I want to prevent -
hyphens while allowing one .
decimal. In my search, the answers on SO talk about keyUp/Down
events, I am not sure if this was possible to get keycode
in the change event
& similar question here does not have an answer
My goal: I only want to allow the user to enter numbers, with a max of ONE .
decimal only.
How to get/watch the keycode, from the textBox change event
?. However, adding the type="number"
allows hyphens -
which I do Not want!
(Or is there an easier way to validate textbox numbers for things like cost?)
$('#table').on('change', '.cost', function () {
var keyVal = $(this).event; //.val;
var keyValKeyCode = $(this).event.keyCode;// undefined?
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(keyVal.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(keyVal.keyCode == 65 && (keyVal.ctrlKey === true || keyVal.metaKey === true)) ||
// Allow: Ctrl+C
(keyVal.keyCode == 67 && (keyVal.ctrlKey === true || keyVal.metaKey === true)) ||
// Allow: Ctrl+X
(keyVal.keyCode == 88 && (keyVal.ctrlKey === true || keyVal.metaKey === true)) ||
// Allow: home, end, left, right
(keyVal.keyCode >= 35 && keyVal.keyCode <= 39) ||
//Allow numbers and numbers + shift key
((keyVal.shiftKey && (keyVal.keyCode >= 48 && keyVal.keyCode <= 57)) || (keyVal.keyCode >= 96 && keyVal.keyCode <= 105))) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((!keyVal.shiftKey && (keyVal.keyCode < 48 || keyVal.keyCode > 57)) || (keyVal.keyCode < 96 || keyVal.keyCode > 105)) {
// only allow ONE decimal
if ($(this).value < 0 || $(this).value > 500) // allow upto 500$
return;
keyVal.preventDefault();
}
)};