Function to use with multiple elements
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/
精彩评论