Alex Neigher
Alex Neigher

Reputation: 907

Persist text in html input during user input

I'm trying to append "USD" following user generated text as a unit in an html input. Right now I have some jquery that appends a $ before any input text, and then rebuilds the input, on each keyup

   $('#pledge_amt_gross_total').on('keyup',function(){
      var text = this.value;
      $(this).val("");
      if (text.indexOf("$") == -1){
         text = "$ " +text;
       }
      $(this).val(text);

    }) 

This works for anything before the user input text, but when I try to append anything after the user text, it doesnt work right.

Upvotes: 3

Views: 412

Answers (2)

Phil-R
Phil-R

Reputation: 2253

I've made a version with a regex to find the number in the input and to wrap it in what you want. I added a timeout to prevent moving the cursor before user has finished his input. Try it in this fiddle

The code :

var formatTimeout;
$("#pledge_amt_gross_total").on("keyup", function() {
    var self = $(this);
    clearTimeout(formatTimeout);
    formatTimeout = setTimeout(function() {
        var regex = /\d+/;
        var amount = self.val().match(regex);
        if (amount.length > 0) {
         self.val("$ " + amount + " USD");   
        } else {
              self.val("");       
        }   
    }, 1000);
});

You can change the time before the format is applied in the setTimout function if you want it to be faster or slower.


Edit :

If you want any number to be concat in the format : fiddle

var formatTimeout;
$("#pledge_amt_gross_total").on("keyup", function() {
    var self = $(this);
    clearTimeout(formatTimeout);
    formatTimeout = setTimeout(function() {
        var regex = /\d+/g;
        var amount = self.val().match(regex);
        if (amount.length > 0) {
         self.val("$ " + amount.join("") + " USD");   
        } else {
              self.val("");       
        }   
    }, 1000);
});

I replaced the regex to be a global regex that will find any number. Then I join the numbers into one.

Upvotes: 4

Jordan
Jordan

Reputation: 1433

Just change

if (text.indexOf("$") == -1){
    text = "$ " +text;
}

to

if (text.indexOf("$") == -1){
    text = "$ " +text;
}
if (!(test.indexOf("USD") >= 0)){
    text = text + " USD";
}

Upvotes: 2

Related Questions