开发者

How do I insert a space after a character in a textbox, depending on the total characters entered, JQuery?

Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks


My Solution, Although it's basic:

$(document).ready(function(){

    $('#postcode').blur(fu开发者_开发知识库nction(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{ 
            document.write('OOPS!');}
    }); 
});


$('#postcode').blur(function()
{
    $(this).val( $(this).val().substring( 0, -3 ) + ' ' + $(this).val().substring( -3 ));
}


You can use a RegExp to replace the last 3 characters with a space plus the same 3 characters:

$('#postcode').blur(function(){
  $(this).val($(this).val().replace(/...$/, ' $&'));
});

Try it: http://jsfiddle.net/PJMDp/1/

If you really must count 3 characters, you should use slice, not substring:

$('#postcode').blur(function(){
  var postcode = $(this), val = postcode.val();
  if(val.length > 3)
    postcode.val(val.slice(0, -3)+' '+val.slice(-3));
});

Try it: http://jsfiddle.net/PJMDp/2/


Have you considered using something like MAsked Input Plugin?

I think it may be of use if properly adapted.


Another option is to use a regex replace:

$('#postcode').blur(function() {
     var str = $(this).val();

     // I assume that since the example had 6 characters that this was the min you were looking for
     if(str.length >= 6) {
         $(this).val(str.replace(/.{3}$/, " $&"));
     }
});


The best way I'd say to make sure your postcode is always correctly formatted, without having to worry about the length of the postcode, do the following:

$("#postcode").bind("blur", function(){
    var postcode_fix = $(this).val().toUpperCase().replace(/ /g,'');
    postcode_fix = postcode_fix.slice(0, -3)+' '+postcode_fix.slice(-3);
    $(this).val(postcode_fix);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜