简体   繁体   中英

Writing my first jQuery plugin

Good Day,

I'm trying to write my first jQuery plugin. I believe it to be a simple one. When I focus in on a textbox, I want to remove any currency formatting (ie removing '$', ',', and '.') When I focus out of a textbox, I want to apply numeric comma formatting.

(function($) {
    $.fn.enableCommify = function() {
        $(this).on('focus', function () {
            var currentValue = $(this).val().trim();
            var stripped = currentValue.replace(',', '');
            $(this).val(stripped);
        });

        $(this).on('focusout', function () {
            var currentValue = $(this).val();
            $(this).val(currentValue.toLocaleString());
        });
    }
}(jQuery));

and when I use it:

$('.commify').enableCommify();

but it's not working. What else am I missing?

ps I'm aware that there are plugins that do this, I'm just trying to learn how to write one then move on to bigger things.

TIA,

coson

toLocaleString() only adds commas when it's applied to a number. But $(this).val() is a string, not a number. Use parseInt() to convert it to a number.

Also, to replace multiple matches of a string, you need to use a regexp with the g modifier.

 (function($) { $.fn.enableCommify = function() { $(this).on('focus', function() { var currentValue = $(this).val().trim(); var stripped = currentValue.replace(/,/g, ''); $(this).val(stripped); }); $(this).on('focusout', function() { var currentValue = parseInt($(this).val(), 10); $(this).val(currentValue.toLocaleString()); }); } }(jQuery)); $('.commify').enableCommify(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="commify"> 

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