【问题标题】:How do I not allow typing in a text input field using jQuery?如何不允许使用 jQuery 在文本输入字段中输入内容?
【发布时间】:2011-01-25 16:55:58
【问题描述】:

我在文本输入字段上使用 jQuery datepicker,我不想让用户使用键盘更改文本输入框中的任何文本。

这是我的代码:

$('#rush_needed_by_english').keydown(function() {
  //code to not allow any changes to be made to input field
});

如何不允许使用 jQuery 在文本输入字段中进行键盘输入?

【问题讨论】:

    标签: jquery events keyboard keydown


    【解决方案1】:
    $('#rush_needed_by_english').keydown(function() {
      //code to not allow any changes to be made to input field
      return false;
    });
    

    【讨论】:

    • 这是否涵盖粘贴事件?如果我单击该框并输入 ctrl-V 会怎样?
    • 使用 keypress 而不是 keydown。 keypress 仍将允许 tab、ctrl-v 等,而 keydown 会阻止所有键。 @Cheeso,我可能迟到了 5 年才回答你的问题,但是....我回答了!
    【解决方案2】:

    您可以简单地将字段设置为只读:

    $('#rush_needed_by_english').attr('readonly', 'readonly');
    

    如果你使用的是 jQuery 1.6+,你应该使用 prop() 方法来代替:

    $('#rush_needed_by_english').prop('readOnly', true); 
    // careful, the property name string 'readOnly' is case sensitive!
    

    或者放弃 jQuery 并使用纯 JavaScript:

    document.getElementById('rush_needed_by_english').readOnly = true;
    

    【讨论】:

      【解决方案3】:

      你可以:

      $('#rush_needed_by_english').attr('disabled', 'disabled');
      

      【讨论】:

      • 不,这会使该字段看起来也被禁用,我正在努力避免这种情况。我只是不希望他们能够打字。
      • 另一个禁用属性的问题,这些字段不会传递给服务器
      猜你喜欢
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多