Andreas BB
Andreas BB

Reputation: 51

Convert dot to comma in input type=number

I am trying to come up with a solution for converting dot to comma in an input field with type="number", using either JS or JQuery.

The problem is two-fold:

1) It needs to replace the dot no matter where it is located in the input field. Values can be for example:

0.50

.45

12.45

12.

2) I can't use keyup as the trigger. This field is being populated by an externally connected scale, which sends the number, including the dot, in one go.

I hope someone can help with this, it's really doing my head in.

** UPDATE ** I managed to get this piece of code to work, but only if the input is TEXT. If I use NUMBER it just wipes the input clean (and I need it to be NUMBER in order to perform other on-page calculations with the number).

document.getElementById('purchaseQuantity').addEventListener('input', function() {
  document.getElementById('purchaseQuantity').value = this.value.replace('.', ',')
});

Thanks,

Upvotes: 0

Views: 3204

Answers (2)

Jakob Povsic
Jakob Povsic

Reputation: 74

var numComma = (value.toString()).replace(".", ",")

Convert the number to string and then use .replace(".",",")

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use a hidden field with name and update the value within the handler.

document.getElementById('number').addEventListener('input', function() {
  document.getElementById('hidden').value = this.value.replace('.', ',')
})
<input type="number" id="number" />
<input type="hidden" name="number" id="hidden" />

Upvotes: 1

Related Questions