开发者

Function to use with multiple elements

开发者 https://www.devze.com 2023-04-09 17:51 出处:网络
I have modified a function to meet my need. This is what I have written to restrict multiple repetition of dots:

I have modified a function to meet my need. This is what I have written to restrict multiple repetition of dots:

$('#title').val(){
    replace(/\.{2,}/g, '.');
});

Is it co开发者_JAVA技巧rrect? How can I make this in function so I can call with every element of the form?


1. Here is your code turned into a jQuery function/plugin.

jQuery.fn.singleDotHyphen = function(){
    return this.each(function(){
        var $this = $(this);
        $this.val(function(){
            return $this.val()
                .replace(/\.{2,}/g, '.')
                .replace(/-{2,}/g, '-');    
        });
    });
}

2. Here is how you use it

$('selector').singleDotHyphen();

3. Here is the demo


Something like this would work -

$('input[type=text],textarea').blur(function () {
    $(this).val(function () {
        return $(this).val().replace(/\.{2,}/g, '.');
    });
});

That would apply your RegEx to every 'text' or 'texarea' input field once it lost focus. Here's a demo - http://jsfiddle.net/xcBFx/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消