Change comma per point

Asked

Viewed 720 times

5

I want when a user type , (comma), this is replaced by . (point). But when I insert the script below, it shows no result.

Can someone help me find the mistake?

function substituiPonto(){
    valor = document.calcform.visor.value;
    while(valor.indexOf(".") >= 0) {
        novoValor = valor.replace(",",".");
    }
    valor = novoValor;
}
<body>
    <form name="calcform" method="post" action="">
        <input type="text" name="visor" id="visor" value="" onKeyPress="substituiPonto()"/>
    </form>
</body>

  • Remember to mark an answer as certain if any has solved your friend problem, so other people who search will also be helped.

4 answers

5


Welcome to Stackoverflow @Moises ;)
In your function you are just taking the value of the input document.calcform.visor.value, transforming him novoValor = valor.replace(",",".") and attributing it to the variable valor = novoValor, but at no time is setting the value of the input with this variable.
Put this at the end of its function and it should already work:

function substituiPonto(){
    ... Faz o tratamento da string aqui
    document.calcform.visor.value = valor; // coloca o valor no input novamente
}

But there’s a simpler way to do what you need:

function substituir(el) {
    el.value = el.value.replace(",", ".");
}
<input type="text" onkeyup="substituir(this);" />

5

Your code does not work since you are using the replace to exchange points (.) for "nothing" ('').

Besides, I think the loop while not so necessary in this situation.


You can then do something more or less like this:

document.querySelector('#field').addEventListener('keyup', (event) => {
  const el = event.target
  if (el.value.includes(',')) {
    el.value = el.value.replace(/,/g, '.')
  }
})
<input type="text" id="field" />

Basically, we created a Listener to the event keyup which will check if the field value has a comma. If it has, the comma will be replaced by the dot.

Note that you can also use the method indexOf instead of includes if you wish.

Reference:

3

You’re trading the "." for an empty value, replace has to be like this

replace(",", ".")

1

Use the following code:

<html>
    <body>
        <form name="calcform" method="post" action="">
            <input type="text" name="visor" id="visor" value="" onKeyPress="substituiPonto()"/>
        </form>

    <script>
    function substituiPonto(){
    valor = document.calcform.visor.value;

    document.getElementById("visor").value = valor.replace(",", ".");
    }
    </script>
    </body>
</html>

Using the function replace(",", ".") to make your replacement.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.