Reputation: 952
I am using a script to format the input for my textbox. I only want to use the characters -
and .
1 time and only be able to add numbers into this textbox. After editing I want to round the input to 2 decimals.
I have no problems with the input.
When I want to delete the input I run into problems.
I am not able to delete the input in Mozilla Firefox. I dont have any issues in Google Chrome or Internet Explorer.
Does someone know how I can solve this issue?
Here is my script:
<input type="text" class="groupOfTexbox" onchange="setTwoNumberDecimal(this)" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
$(document).ready(function() {
$('.groupOfTexbox').keypress(function (event) {
return isNumber(event, this)
});
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (
(charCode != 45 || $(element).val().indexOf('-') != -1) &&
(charCode != 46 || $(element).val().indexOf('.') != -1) &&
(charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
JSFiddle: http://jsfiddle.net/5zduh3a7/1/
Upvotes: 1
Views: 229
Reputation: 944
Include backspace (code = 8) into your whitelist:
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode != 45 || $(element).val().indexOf('-') != -1) &&
(charCode != 46 || $(element).val().indexOf('.') != -1) &&
(charCode < 48 || charCode > 57) &&
(charCode != 8)) {
return false;
}
return true;
}
Also note that it's better to use keydown
/keyup
instead of keypress
for such cases. It seems that IE and Chrome doesn't trigger keypress
events for some special keys like backspace. That's why your code works in IE and Chrome even without whitelisting backspace key code.
Upvotes: 3