Replacing a dot using JavaScript instead removes everything

  • A+
Category:Languages

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?

 


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.

Comment

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