【问题标题】:unable to edit letters in textbox on adding space after three letters in textbox in jQuery无法在 jQuery 中的文本框中添加三个字母后添加空格时编辑文本框中的字母
【发布时间】:2017-12-07 01:30:09
【问题描述】:

如何从以下文本框中重新编辑字母

$('.zip-code').on('keypress change', function () {
  $(this).val(function (index, value) {
    return value.replace(/\W/gi, '').replace(/(.{3})/g, '$1 ');
  });
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  />

上面的代码在 3 个字母后给出了空格,但无法重新编辑该字母

以下是面临的问题:

  1. 应删除整个邮政编码以编辑文本框中的字母
  2. 如果邮政编码输入错误并且需要对其进行编辑,则无法编辑邮政编码字段中的字母。
  3. 编辑邮政编码后,字母移到末尾。

【问题讨论】:

  • 我无法清楚地理解这些问题。
  • 请运行代码并在文本框中添加一些值并尝试编辑谢谢
  • 你应该给出一些预期的输出。
  • 例如:如果我添加“123 456”那么应该能够编辑为“103 456”而不删除所有并再次添加,就像我应该删除2并从同一位置添加0一样。谢谢

标签: jquery


【解决方案1】:

您的问题是几个问题。首先,您要使用 keyup 来获取值,否则它将在设置键值之前触发,并且在调用时不会给出准确的值。其次,您的正则表达式正在运行,而您可能仍在键入,这会强制光标到末尾。您可以使用计时器 (Borrowed from this answer) 来克服这个问题。

试试下面的sn-p,我相信这可以完成你的目标。

var typingTimer;                //timer identifier
var doneTypingInterval = 1000;  //time in ms, 1 second for example
var $input = $('.zip-code');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(formatZip, doneTypingInterval);
}).on('keydown', function () {
  clearTimeout(typingTimer);
});

function formatZip () {
  $input.val(function (index, value) {;
    var str = value.replace(/\W/gi, ''),
        newVal = [str.slice(0, 3), ' ', str.slice(3,6)].join('');
    return newVal;
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label" for="credit-card">zip Code</label>
<input type="text" maxlength="7" class="zip-code" value="" autocomplete="off"  />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多