2017-02-17 4 views
3

私が達成したいのは、四分の一がスペースで置き換えられた後です。 私が1234123412341234の入力でキーを押すと書いているように、 私は1234 1234 1234 1234を達成したいと思います。4番目の入力値ごとにスペースjqueryで置き換えますか?

<input type="text" id="number" maxlength=19 /> 

そして、ここにあるので、このコードは唯一、第四の後にスペースを作成します1234 123412341234. しかし、入力値の残りのために行う方法

$('#number').on('keypress', function() { 
    if (this.value.length >= 4) { 
    this.value = this.value.slice(0, 4) + ' '+this.value.slice(5, 9); 
    } 

をJS?前もって感謝します。

+0

jQueryのここでのソリューションではありません、あなたは標準JSでこれを行うことができます - http://stackoverflow.com/questions/32030727/replace-every-nth-character-from- a文字列 – G0dsquad

答えて

4

これは、あなたが

注用それのバグあなたは高速入力ビットを探しているものかもしれないが、私は、ATM <それを固定している - 問題ないはず

$(function(){ 
 
    $("input").keydown(function(){ 
 
     if ((($(this).val().length+1) % 5)==0){ 
 
      $(this).val($(this).val() + " "); 
 
     } 
 
    });   
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input />

+0

簡単なtnx :) – NemanjaD

+0

あなたの歓迎:) –

5

置き換えを使用して4文字を検索できます。

console.log('1234123412341234'.replace(/.{4}/g, '$& '));

+0

素晴らしいソリューション。 –

+0

入力時に正しく動作しません。 – Mohammad

関連する問題