简体   繁体   中英

Add special character at end of input fields string, jquery automatically adding comma

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)

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+'%');        
        });

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 .

$('.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/

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM