0

I'm attempting to creating a numerical field in a form -- the field automatically converts numbers to currency. Everything works fine, except for the 'minus' sign. It seems like a simple fix, but escaping with regex in javascript/jquery doesn't seem to work/I'm not applying it correctly. Here's my code:

function format() {
  // unformat the value
  var value = this.value.replace(/[^0-9\.-]+/g, "");
  var on = /^(\d{1,3})((?:\d{3})*)$/.exec(value);
  var commas = on[2].replace(/(\d{3})/g, ',$1');
  this.value = '$' + [on[1], commas, on[3]].join('');
}

$(document).ready(function() {
  $('.we').on('keyup', format);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" class='we' />
<input type="text" class='we' />

Thanks for assistance,

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
011289User
  • 55
  • 4
  • It looks like the code contains a lot of errors. Do you wanna tell what you are trying to achieve? It is always better to use `.blur()` rather than `keyup`. – Praveen Kumar Purushothaman Nov 05 '16 at 18:04
  • I'm using keyup because of a feature I plan to implement down the road. It's a request from some of my users that as they type the field changes for them... – 011289User Nov 05 '16 at 18:08
  • What exact problem with the minus sign are you trying to fix? A negative number? An accidental minus sign in the middle of the number? If it is a negative number, a simple `if` test at the beginning to see if there is a minus there and then take it out and set a negative flag would solve the problem. Random minus signs can easily be removed with `string.replace();` – Scott Marcus Nov 05 '16 at 18:11
  • Right, Praveen code did not work for me earlier. I don't want the minus sign to be removed if the user needed to type a negative number. Any changes to the code I've added in the question would be best. – 011289User Nov 05 '16 at 18:18
  • I just want the user-entered negative numbers to also be formatted just like the positive numbers: with commas and the dollar sign added -- – 011289User Nov 05 '16 at 18:38

0 Answers0