Reputation: 7215
I have a quantity text box which should not allow negative sign, and '.' character.
I have tried a jquery block but it allow '.'. I want to block '.' in a text box
$(document).ready(function () {
$('#used_quantity').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="used_quantity">
Upvotes: 1
Views: 873
Reputation: 22510
Do with keydown
event.Only match with key value, not with string of the input
Updated
with backspace
$(document).ready(function() {
$('#used_quantity').keydown(function(event) {
if ((event.which != 46) && (event.which < 48 || event.which > 57) && (event.which != 8)) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="used_quantity">
Upvotes: 3
Reputation: 188
Try this :
$('#used_quantity').bind("change input", function () {
var value = $(this).val().replace(/([^0-9].*)/g, "");
$(this).val(value);
})
Upvotes: 0
Reputation: 113
Please check this code. It will work. Remove
if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
(event.which < 48 || event.which > 57))
condition to
if ((event.which < 48 || event.which > 57) && event.which != 45) {
Check jsliddle EXAMPLE HERE
Upvotes: 1
Reputation: 1103
Change the condition as (((event.which == 46 || event.which == 45 || $(this).val().indexOf('.') != -1)) || (event.which < 48 || event.which > 57))
. on keypress
event
$(document).ready(function() {
$('#used_quantity').keypress(function(event) {
if (((event.which == 46 || event.which == 45 || $(this).val().indexOf('.') != -1)) || (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="used_quantity">
Upvotes: 0
Reputation: 14562
You need to modify the condition to event.which == 46 || event.which == 45
to ignore the .
and the -
respectively.
$(document).ready(function() {
$('#used_quantity').keypress(function(event) {
if (event.which == 46 || event.which == 45 || event.which < 48 || event.which > 57) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" id="used_quantity">
Upvotes: 1