Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a dot using JavaScript instead removes everything

I've walked into a strange problem. When trying to replace a dot on a number input, instead of replacing just that dot, it clears out the entire input.

$("[data-input-payment-id]").on("keyup", function(e) {
  var test_value = $(this).val().replace(/\./g, "");
  $(this).val(test_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-input-payment-id="12">

JSFIDDLE

How do I change it so it only removes the dots?

like image 270
Ellisan Avatar asked Jul 30 '18 09:07

Ellisan


1 Answers

I think (guessing) it's because you use type="number". Then digits followed by a dot, e.g. 123., isn't a valid number, and val returns blank.

You could try this instead:

$("[data-input-payment-id]").on("keyup", function(e) {
  var test_value = this.value.replace(/[^\d,]/g, "");
  $(this).val(test_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-input-payment-id="12">

This uses normal text type and filters out anything but digits in the replace.

Edit:
Changed the regex to match anything but numbers and commas.

like image 144
SamWhan Avatar answered Oct 18 '22 12:10

SamWhan