how to format variable with jquery Mask

Asked

Viewed 1,942 times

0

People use the plugin jQuery Mask Plugin v1.13.4

I have a div where I report a value as follows:

$('#v_pg').text('PAGA R$ ' + valor_pago);

Use Jquery to update the value inside the div. But I wanted it to be formatted by Mask as follows:

$('').mask('00.000.000,00', {
    reverse: true
});

Does anyone know if there’s a way to do it? Or if there’s another way?

  • 1

    This plugin will only work with inputs...

  • @Kennyrafael, the plugin works with Divs also.

  • actually the plugin works on div yes

1 answer

1


In his div, try to separate the content you want to put static text mask.

Something like that:

<div id="#v_pg">
   PAGA R$ <span class="valor_pago"></span>
</div>

Finally, you can put the mask as follows:

$('.valor_pago').mask('00.000.000,00', {
    reverse: true
});

Should work.

Another alternative is to use the attribute data-mask in the element. I have never particularly tested with elements other than inputs but theoretically it should work:

<div id="#v_pg">
   PAGA R$ <span class="valor_pago" data-mask="00.000.000,00"></span>
</div>

If you have questions, you can ask in the comments.

  • Well your first way went almost right hahaha. I have 2 problems. 1 When the number is negative the Mask is converting to positive, 2 I need to have my jquery round the number to only 2 decimal places after the comma. Could you help me?

  • 1

    About positive and negative, I’m not sure Igor Escobar’s lib supports patterns like that. I ask you to take a look at his repository and see if it is possible to support negative numbers: https://github.com/igorescobar/jQuery-Mask-Plugin. About 2 decimal places, try using the method toFixed() of JS. Example: valor_pago.toFixed(2);.

  • perfect, thank you very much

Browser other questions tagged

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