Replacing a dot using JavaScript instead removes everything

  • A+

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=""></script> <input type="number" data-input-payment-id="12">


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


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=""></script> <input data-input-payment-id="12">

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

Changed the regex to match anything but numbers and commas.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: