2

I am adding % symbol at the end of the string on keyup event, first I get the current value of input field and then split('%') and then I use following code

$('.percent input[type=text]').val(str+'%');

But this also adding comma after newly added character. jsfiddle

Also Would love to do it by using css but the condition is only that there should not be any image used for it neither positioning used.(Can I use :after or :befor)

3
  • it would be much easier to take that percentage sign out of the input and put it after it Commented Aug 29, 2013 at 8:56
  • @slash: yes slash I know that but I thought I will look good if I included it inside input field as my Input field using customized style Commented Aug 29, 2013 at 8:58
  • 1. doesn't look better; 2. it is complicating the user experience Commented Aug 29, 2013 at 9:32

4 Answers 4

1

IMO the problem was the split function. Try this:

$('.percent input[type=text]').on('keyup',function(){
            var oldstr=$('.percent input[type=text]').val();
            var str=oldstr.replace('%',''); 
            $('.percent input[type=text]').val(str+'%');        
        });
Sign up to request clarification or add additional context in comments.

Comments

0

Javascript .split() method returns comma seperated data, that is why your data is comma seperated. If all you wish to do is remove the first symbol you could use .substr() - read about it here.

Comments

0
$('.percent input[type=text]').on('keyup',function(e){
            var oldstr=$('.percent input[type=text]').val();
            var tokens = oldstr.split('%');
            var suffix = tokens.pop() + '%';
            var prefix = tokens.join("");
            $('.percent input[type=text]').val(prefix+suffix);
});

JS Fiddle: http://jsfiddle.net/uU8Lf/4/

Comments

0

A little late now, however I couldn't help but notice the constant reuse of the element's class/type throughout both answers. Is it not beneficial/best practice to use 'this' keyword within the '.on' callback function like so:

$('.percent input[type=text]').on('keyup',function(){
    var oldstr=$(this).val();
    var str=oldstr.replace('%',''); 
    $(this).val(str+'%');        
});

Please correct me if I'm wrong, and yes, I'm being picky here :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.