How to insert a space after a character in a text field, depending on all the characters entered, jQuery?

Is it possible to add a space to the text field depending on the common characters entered by the user.

For example, if a user types “LU33RT” into the blur, I would like it to display “LU3 3RT”. The rule I'm going to include is counting 3 characters on the right, then add a space.

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

Any help would be greatly appreciated, thanks


My solution, although it is basic:

$(document).ready(function(){

    $('#postcode').blur(function(){
        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!');}
    }); 
});
+3
source share
5 answers

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

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

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

3 , slice, substring:

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

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

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

Another option is to use regular expression replacement:

$('#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}$/, " $&"));
     }
});
0
source

Do you find using something like a MAsked Input Plugin ?

I think it can be useful if it is properly adapted.

0
source

The best way to tell your zip code to be formatted correctly without worrying about the length of the zip code is as follows:

$("#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
source

Source: https://habr.com/ru/post/1777690/


All Articles