user3386779
user3386779

Reputation: 7215

prevent dot in a text box

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

Answers (5)

prasanth
prasanth

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

Anoop Babu
Anoop Babu

Reputation: 188

Try this :

$('#used_quantity').bind("change  input", function () {
    var value = $(this).val().replace(/([^0-9].*)/g, "");
    $(this).val(value);
})

Upvotes: 0

Heshankit
Heshankit

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

Jino Shaji
Jino Shaji

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

Nisarg Shah
Nisarg Shah

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

Related Questions