I need a mask that always puts the negative sign in front of the typed value

Asked

Viewed 117 times

0

I need it this way: -20,00

  • Publish the code you’ve tried and the difficulties faced and justify why you couldn’t do the mask.

  • Hello Marcos Ricardo, welcome! Read this post so they don’t close or negatively answer your questions https://answall.com/help/mcve

  • Also interesting to mark the answer that served as accepted, see how and why in this post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • Thanks to everyone, I managed to remove my doubts with the two answers obtained and I took full advantage of one of them. I am beginner in the stack!

2 answers

1

A very simple implementation for this problem:

$('#mask').keyup(function(){
  if((this.value.search('-') == -1 && this.value.length > 0 )){
    $(this).val('-' + this.value);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"  id="mask" >Máscara

  • Thanks friend! Solved very well.

0


Just concatenate the - (minus) signal to the returned value

$('input').change(function(){
 var input = "-" + ($('#numInput').val());

 console.log(input);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="numInput">

To use in mathematical calculations requires turning the comma into a point

$('input').keyup(function(){
var input = "-" + $($(this)).val().replace(',','.');

 var result = ((100+parseFloat(input)).toFixed(2));

 console.log(result);

 var resultVirgula = result.replace('.',',');

 console.log(resultVirgula);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="numInput">

Browser other questions tagged

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