Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist text in html input during user input

Tags:

html

jquery

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.

like image 981
Alex Neigher Avatar asked Nov 19 '25 18:11

Alex Neigher


1 Answers

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.

like image 195
Phil-R Avatar answered Nov 21 '25 06:11

Phil-R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!