如何使用jquery在keyup上添加新值到div每n位? [英] How to add new value on keyup to div every n digit with jquery?

查看:36
本文介绍了如何使用jquery在keyup上添加新值到div每n位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每次用户输入 3 位数字时自动列出数字.输入的数字应自动出现在 div 中.

I want to auto list numbers every time the user types in 3 digits. The input numbers should appear in the div automatically.

$("#lister").on("keyup", function() {
  var mxlen = $(this).data("mxlen");
  var input = $(this).val();
  if (input.length == mxlen) { //if input==3
    $('#num_list').append('<li>' + input + '</li>');
    $(this).html(''); //clear input after appended
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num_list"></div>
<input type="number" id="lister" data-mxlen="3" />

我的代码的问题是它重复了相同的数字,并且在追加后没有清除输入.

The problem with my code is that it repeats the same numbers and does not clear the input after appending.

推荐答案

你的代码已经差不多了,你只需要使用 val('') 来重置值.

Your code is almost there, you just need to use val('') to reset the value.

另请注意,您可以通过使用 slice(0, mxlen) 在快速键入时将值限制为 3 个字符来使逻辑更加健壮,并且还将检查从 == 更改为>= 出于同样的原因.

Also note that you can make the logic more robust by using slice(0, mxlen) to restrict the value to 3 characters when typing quickly, and also change the check from == to >= for the same reason.

$("#lister").on("input", function() {
  let $el = $(this);
  var mxlen = $el.data("mxlen");
  var input = $el.val();
  
  if (input.length >= mxlen) {
    $('#num_list').append('<li>' + input.slice(0, mxlen) + '</li>');
    $el.val('');
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num_list"></div>
<input type="number" id="lister" data-mxlen="3" />

最后要注意的是,诸如 -e 之类的字符对于 type=number" 输入中的条目是有效的字段,但是它们对于字段返回的值无效.因此,当使用这些字符时,length 检查会得到不一致的输出.

One last thing to note is that characters such as - or e are valid for entry in a type="number" input field, however they are not valid for the value returned from the field. As such the length check will get inconsistent output when these characters are used.

根据您的用例,您可能最好使用标准的 type="text" 检查并手动将输入限制为数值.

Depending on your use case you may be better off with a standard type="text" check and manually restricting the input to numerical values.

这篇关于如何使用jquery在keyup上添加新值到div每n位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆