简体   繁体   中英

How can I add minus sign in jquery?

My html code :-

<input type="text" id="test">
<span class="display"></span>

My jquery code :

$("#test").keyup(function(e){
  $('span.display').text(formatCurrency($(this).val()));
  this.value = this.value.replace(/[^0-9\.]/g,'');
});

Demo and full code is like this : https://jsfiddle.net/oscar11/nbLbb037/

I want the input text can enter this : -10000000

And the result who displayed in class display is : -10.000.000

How can I add minus ( - ) sign?

Need to change code like below:-

output = output.reverse();
if(output[1] == '.'){
   output.splice(1, 1);
   formatted = output.join("");
}else{
   formatted = output.join("");
}

And every thing will be fine.

Example:-

 $("#test").keyup(function(e){ $('span.display').text(formatCurrency($(this).val())); this.value = this.value.replace(/[^0-9\\.-]/g,''); }); // format currency on pagu and revisi var formatCurrency = function(num){ var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null; if(str.indexOf(",") > 0) { parts = str.split(","); str = parts[0]; } str = str.split("").reverse(); for(var j = 0, len = str.length; j < len; j++) { if(str[j] != ".") { output.push(str[j]); if(i%3 == 0 && j < (len - 1)) { output.push("."); } i++; } } output = output.reverse(); if(output[1] == '.'){ output.splice(1, 1); formatted = output.join(""); }else{ formatted = output.join(""); } return(formatted + ((parts) ? "," + parts[1].substr(0, 1) : "")); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test"> <span class="display"></span> 

adding a minus sign is very easy, just replace

this.value = this.value.replace(/[^0-9\.]/g,'');

with following

this.value = this.value.replace(/[^0-9\.-]/g,'');

updated js fiddle is https://jsfiddle.net/nbLbb037/3/

But. You need to use regular expression test to verify exact currency test. Try exploring js regular expression test for your "formatCurrency" function. Of course thats purly upto you. Current solution will let you move further.

I have updated the regular expression js code on fiddle. Refer to https://jsfiddle.net/nbLbb037/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM