How to automatically insert a space after every comma in a textbox using JQuery?
I trying to write a script using jQuery, it is suppose to automatically put a space after every comma "," in o开发者_高级运维rder to separate a sequence of numbers that user input in an input field. e.g. if they enter (45,68,95,23) it becomes (45, 68, 95, 23) when the user moves away from the input field.
Got this to check if the input has a comma or not
$("#test").blur(function() {
if(this.value.indexOf(",") !== -1) {
alert('got a comma');
}
});
Simply split the input value by commas, trim the spaces off each item, then join the resulting array back together with a comma and space.
$("#test").blur(function () {
this.value = $.map(this.value.split(","), $.trim).join(", ");
});
$('#test').blur(function(){
$(this).val(function(i,oldValue){
return oldValue.replace( /,\s*/g, ', ' );
});
});
Or, with less jQuery:
$('#test').blur(function(){
this.value = this.value.replace( /,\s*/g, ', ' );
});
this.value=this.value.replace(/,/gim,', ');
Using regex, this will normalize the whitespace around each comma to one U+0020 space character after, happening when the text box loses focus after changing value. It also trims whitespace (or a stray comma) from the beginning and end:
$("#test").change(function() {
this.value = this.value.replace(/\s*,\s*/g, ', ').replace(/^,?\s*|,?\s*$/g, '');
});
Regex is also helpful for telling the user whether his input is valid or not. Try this demo:
$("#test").focus(function() {
$(this).removeClass('valid invalid');
}).blur(function() {
this.value = this.value.replace(/\s*,\s*/g, ', ').replace(/^,?\s*|,?\s*$/g, '');
if(/^(?:[\d.](?:, )?)*$/.test(this.value)) {
$(this).addClass('valid');
} else {
$(this).addClass('invalid');
}
});
精彩评论