Reputation: 1812
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)
Upvotes: 2
Views: 7700
Reputation: 376
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 :)
Upvotes: 0
Reputation: 94469
$('.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/
Upvotes: 0
Reputation: 1720
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.
Upvotes: 0
Reputation: 503
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+'%');
});
Upvotes: 1