【问题标题】:How can I get each character added in a form field using jQuery/JavaScript如何使用 jQuery/JavaScript 在表单字段中添加每个字符
【发布时间】:2015-09-26 07:34:13
【问题描述】:

我想向用户显示一条错误消息,如果他在文本字段中输入的字符多于指定的字符,并且此规范可能会随着提供的初始字符而改变。除此之外,我需要处理用户出于某些业务目的输入的每个字符。 例如

让我们考虑一个信用卡字段。

不同的信用卡类型有不同的最大长度。我想阻止用户在字段中输入比他们的信用卡类型允许的更多的字符。

但是,只有当用户提供的信用卡首字母很少时,才能检测到信用卡类型。

我的方法是尝试在每次按键时检测信用卡,并根据检测到的信用卡类型设置字段的最大长度。如果未检测到,则将最大长度保持为 19(这是所有的最大值)

我的尝试

---------------------------------------------------------------------
|   Event    | Problem                                              |
| ------------------------------------------------------------------|
|            |  Change will not be triggered until the user         |     
|  OnChange  | moves out of the field. Since I need this event      |
|            | on every char entered, this is not helpful           |
|-------------------------------------------------------------------|
|            | It gives issues when a user presses the key for a    |
|  KeyDown   | longer duration. Characters are entered multiple     |
|            | times, but this event is triggered only once.        |
|-------------------------------------------------------------------| 
|  KeyUP     | Same as above.                                       |
|-------------------------------------------------------------------|
|  KeyPress  | I am getting older value. The newly added character  |
|            | is not available. Hence incorrect calculation        |
---------------------------------------------------------------------

我有一个使用超时的替代方法,但正在寻找更好的选择。

由于上述原因,我的问题与this one. 不同。

请为此提出一个好的解决方案。

【问题讨论】:

  • 请出示相关代码。
  • 使用 .change(function(){ ... });而不是 keypress();
  • @Ji_in_coding change 仅在 input 元素失去焦点时触发,这听起来不像 OP 想要的行为。
  • 如何使用keydown..并使用“counter”变量?
  • @MohitKanwar 你说你不能用keyup,但是你试过keydown吗?

标签: javascript jquery


【解决方案1】:

试试这个

这将在您更改输入时起作用

$(someTextInputField).on('input',function(e){
  var txtLength =this.value.length;
  var validLength=4;
  if(txtLength > validLength){ 
      this.value=this.value.substr(0, validLength);
      alert("please enter only 4 character");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input id="someTextInputField" type="text">

【讨论】:

  • "keyup" 如果 keypress 事件发生但 keyup 没有帮助。例如长按键事件。
  • 如@Rejith R Krishnan 所述,输入是一个 html 5 事件。 developer.mozilla.org/en-US/docs/Web/Events/input 但在 IE9 及更低版本中存在问题。因此,我们使用 propertychange 事件 msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx 以获得更好的浏览器兼容性。 – Rejith R Krishnan
【解决方案2】:

我认为这可以满足您需要的大多数情况。

这将在每次输入更改时起作用。如果我们输入超过允许的长度,则重置值。

var limit = 10; //your input limit
$(document).on('ready',function(){
    var oldValue = $( "input[type='text']" ).val();
    $( "input[type='text']" ).on('keydown',function(e) {
        oldValue = $( this ).val();
    })
    $( "input[type='text']" ).on('input propertychange',function(e) {
        newValue = $(this).val();
        if(newValue.length > limit){
            $(this).val(oldValue);
            alert('String too long.');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text">

更新fiddle

【讨论】:

  • 结合使用“input propertychange”和从“this”获取值而不是 jQuery 选择器对我有用。但是,我仍然不明白为什么。你能解释一下你的代码吗?跨度>
  • @MohitKanwar $(this) 表示我们正在获取绑定的元素,我将其用于排他性。只有在整个 DOM 中只有一个 input[type='text'] 时,$( "input[type='text']" ) 才能正常工作。
  • 是的,但不知何故,从 jQuery 中选择字段返回旧值,而“this”返回新值。 .on('input propertychange') 是什么意思?这是一个不同的事件吗?或者当输入和属性更改都被触发时?
  • input 是一个 html 5 事件。 developer.mozilla.org/en-US/docs/Web/Events/input 但是IE9及更低版本有问题。因此,我们使用propertychange 事件msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx 以获得更好的浏览器兼容性。
  • 输入作用于我们复制和粘贴、文本拖放的大多数情况。
【解决方案3】:

据我了解,这是一个更简单(我相信)的解决方案:

HTML:

<input type="text" id="test" />
<div id="result"></div>

JS:

var maxLength = 10;

$('#test').keypress(function(e){
  if($(this).val().length + 1 > maxLength){
    event.preventDefault();
  }
  else {
    $('#result').html($(this).val() + String.fromCharCode(event.which));
  }
});

在 Codepen 中使用它:http://codepen.io/anon/pen/zGWQvG

【讨论】:

  • 这只会被调用一次,以防长按键。这会影响要输入的多个字符
【解决方案4】:

我建议为按键事件添加 50 毫秒的延迟。 如下。

$('#test').keypress(function(){
  setTimeout(function(){
    $('#debug').append('<br>' + $('#test').val());
  }, 50);


});

example here

【讨论】:

    【解决方案5】:

    $(function() {
      var max_lenght = 5;
      
      $("#myTextInput").keypress(function(event) {
        if ($(this).val().length > max_lenght - 1 && $(this).val().length > 0) {
          event.preventDefault();
          alert("max_length reached");  
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type="text" id="myTextInput" placeholder="type here..." />

    试试这个代码,它检查keypress 是否达到max_lenght 变量(在本例中为5)(我在条件中添加了-1)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2019-04-22
      相关资源
      最近更新 更多