kingzing1
kingzing1

Reputation: 115

Jquery add percent sign to input box

I'd like to have an input box that automatically adds a visible percent sign to the user when entering numbers (not just recognizes it as a percent when submitting). Thus, a user hits "2" and sees "2%"

I'm assuming one could use Jquery to do this fairly easily, but I have no idea how! Any ideas?

Thanks everyone.

Upvotes: 8

Views: 9508

Answers (2)

SLaks
SLaks

Reputation: 887767

You can handle the change event:

$(':input.Percent').change(function() {
    $(this).val(function(index, old) { return old.replace(/[^0-9]/g, '') + '%'; });
});

Upvotes: 16

Puaka
Puaka

Reputation: 1751

On Keyup event

$('input').keyup(function(e) {
    if(e.which != 13) { //13 is enter, you dont want to submit the form on enter
      var value = $.trim($(this).val());
      if(value != '') {
         $(this).val(value +'%');
      }
    } else {
         return false;
    }
});

Upvotes: -1

Related Questions