Juan Camacho
Juan Camacho

Reputation: 746

How can I replace "." by "," character in real time with JQuery?

I would like to control when user writes a number in any input with type="number" and step="any", in real time, JavaScript replaces . character by , character.

I tried with this code, but it's not working:

$(document).ready(function() {
  $('input[type=number,step=any]').replace('.', ',');
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>

<input type="text" />
<input type="number" step="any" />

Upvotes: 1

Views: 357

Answers (2)

Husen
Husen

Reputation: 1587

Please use this code.

$('input[type=number]').keypress(function () {
    $('input[type=number]').val($('input[type=number]').val().replace(/\./g, ','));
});

Upvotes: 1

Luka Kerr
Luka Kerr

Reputation: 4239

As stated in the comments, inside a input with type="number" you cannot enter commas. The number input can accept floating point numbers, including negative symbols and the e or E character, but not commas

You should just use a text input

Try something like this:

$(function() {
  $("input").keyup(function() {
    $(this).val($(this).val().replace(".", ","));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

As an example, this is what happens when you use an input with type="number":

$(function() {
  $("input").keyup(function() {
    $(this).val($(this).val().replace(".", ","));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input" type="number" />

Upvotes: 1

Related Questions