Take value in Currency and remove "." and "," from an input field?

Asked

Viewed 56 times

-1

When the person enters the value in the input field with "." and "," I take this amount and leave only number, I am doing this using the "focusout" method. Because this way when the person type the value changes from an automatic to just number. Be able to do without problem. But if one puts a value of R $ 1.500,00 instead of staying only 1500 this getting 150000.

Below follows code

<div style="max-width: 50%; margin: 50px auto;">
    <input class="form-control" type="text" id="valor-minimo" value="" />
</div>

<div style="max-width: 50%; margin: 50px auto;">
    <input class="form-control" type="text" id="valor-maximo" value="" />
</div>


<script>

    // Pega o valor em Moenda e retira o "." e "." do input valor-minimo
    const $campoValorMin = document.querySelector('#valor-minimo')

    $campoValorMin.addEventListener('focusout', (event) => {

        $valorMin = event.target.value;
        $campoValorMin.value = $valorMin.replace(/[.,]/g, "")
        

    })

    // Pega o valor em Moenda e retira o "." e "." do input valor-maximo
    const $campoValorMax = document.querySelector('#valor-maximo')

    $campoValorMax.addEventListener('focusout', (event) => {

        $valorMax = event.target.value;
        $campoValorMax.value = $valorMax.replace(/[.,]/g, "")

    })
</script>
  • What if one wants to set fewer decimals how it works ? for example R$ 1500,5 ? What value do you expect to interpret

1 answer

0


You need to divide by 100, because by taking out the comma, you’re adding zeros to the right:

    $campoValorMax.addEventListener('focusout', (event) => {

        $valorMax = event.target.value;
        $campoValorMax.value = parseFloat($valorMax.replace(/[.,]/g, "")) / 100
    })

Now, if you need to keep being string, you need to remove not only the comma, but what comes after it too.

   //retira o '.' e depois a ',' juntamente com os dois números depois desta
   $campoValorMax.value = $valorMax.replace(/([.])/g, "").replace(/[,]\d{2}/g,'')
  • 1

    Thank you, Marcos Alexandre, that’s exactly what I needed...

  • Please, we’re here to help.

Browser other questions tagged

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