0

I have a text box that will input a figure in %. What i want to do is that as the user typesin his digits, a '%' sign should get appended at the end. so if some one types in 1.23, what he should see is :- 1% -> 1.% -> 1.2% -> 1.23%. This is what I have written

$('#price').bind('keyup',function(){
    val1 = $(this).val();
    val2 = val1.substr(0,val1.length-1);
    $(this).val(val2+'%');
});

The problem is the cursor comes in after the % sign appended so after 1% if I type '.' the val1 = "1%." and the final result is 1%%. Some help please? If you can tell me how to put the cursor before % or some other solution to the original issue. Thanks a bunch

SNAG
  • 2,011
  • 2
  • 23
  • 43

2 Answers2

3

Adding a percent sign to the text field provides a horrible user experience.

You'd better use a background image, or add the percent sign after the textbox, optionally positioning it so that it seems to be placed inside the box.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • mm.. this is more of a suggestion than answer.. may be it is just me – Selvakumar Arumugam Apr 26 '12 at 19:31
  • 2
    @Vega A literal answer can be: "Use `$(this).val(val2.replace(/[^0-9.]/g,'')+'%');`. I did not post *that* as the answer, because it provides a bad UX. Try it out yourself: http://jsfiddle.net/t4j8C/ (and move the caret to a position other than the end). – Rob W Apr 26 '12 at 19:38
1

Yeah, it's pretty ugly putting things inside of user input. You're better off labeling the field. If you feel you must, look at this question dealing with setting the cursor position.

Set cursor position in an input text field

Community
  • 1
  • 1
FlavorScape
  • 13,301
  • 12
  • 75
  • 117