【问题标题】:How can I bind to the change event of a textarea in jQuery?如何绑定到 jQuery 中文本区域的更改事件?
【发布时间】:2012-07-05 12:27:07
【问题描述】:

我想捕捉<textarea> 是否发生任何变化。就像键入任何字符(删除、退格)或鼠标单击并粘贴或剪切一样。是否有可以触发所有这些事件的 jQuery 事件?

我尝试了更改事件,但它只有在从组件中跳出后才会触发回调。

使用:如果<textarea> 包含任何文本,我想启用按钮。

【问题讨论】:

  • 绑定到按键事件是不够的,因为可以通过鼠标更改文本(从上下文菜单中“粘贴”/“剪切”或拖放)。
  • Textarea onchange detection 讨论了类似的问题。

标签: javascript jquery jquery-ui


【解决方案1】:

试试这个:

$('#textareaID').bind('input propertychange', function() {

      $("#yourBtnID").hide();

      if(this.value.length){
        $("#yourBtnID").show();
      }
});

DEMO

这适用于您所做的任何更改、键入、剪切、粘贴。

【讨论】:

  • @Senthilnathan:Chrome 和 FF 对我来说也不起作用,因为它不是 propertychange 还有input
  • 当心,因为我刚刚发现当在文本区域中按下退格键时,这两个事件都不会在 IE9 中触发(尚未检查旧版本的 IE)。
  • 这些演示使用的是<input type="text">,而不是<textarea>
  • 将 'input propertychange' 更改为 'input change' 以便它在 IE9 中也能正常工作。 paulbakaus.com/2012/06/14/propertychange-on-internet-explorer-9
  • 我看到你在 DEMO 中使用了 ,是认真的吗?
【解决方案2】:

bind 已弃用。使用on:

$("#textarea").on('change keyup paste', function() {
    // your code here
});

注意:上面的代码会触发多次,每个匹配的触发器类型触发一次。要处理这个问题,请执行以下操作:

var oldVal = "";
$("#textarea").on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }

    oldVal = currentVal;
    //action to be performed on textarea changed
    alert("changed!");
});

jsFiddle Demo

【讨论】:

  • on("change", function() .... 部分不适合我。不会触发任何警报,也不会触发控制台日志等任何内容。不过,对于 keyup 来说,它就像一种魅力。
  • @Sebastialonso:on("change", function() ... 仅在文本区域失去焦点时触发。请参考我的earlier question,并在this fiddle 上尝试一下——更改文本区域,然后在文本区域外部单击,您应该会看到更改事件触发。
  • @SNag 该代码无法在 Chrome 45 上运行,但在 FF 41 上运行
  • 如果你在使用 jQuery 1.7 之前的版本时卡住了,那么这不适用
  • 您可能只使用.one("change keyup paste", function ... 而不是.on。 one 事件监听器只触发一次。
【解决方案3】:

使用input 事件。

var button = $("#buttonId");
$("#textareaID").on('input',function(e){
  if(e.target.value === ''){
    // Textarea has no value
    button.hide();
  } else {
    // Textarea has a value
    button.show();
  }
});

【讨论】:

  • 对于 Internet Explorer,这需要 9+,甚至 10+ 才能正常运行。
  • 这个解决方案就像一个魅力。完美克服了 change() 和 keypress() 事件处理程序的限制。非常感谢。
  • 这似乎不适用于粘贴事件?感谢您的帮助。
【解决方案4】:

这个问题需要一个更新的答案,有来源。这就是 实际上 的工作原理(尽管您不必相信我的话):

// Storing this jQuery object outside of the event callback 
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")

// input           :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange  :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {

  // This is the correct way to enable/disabled a button in jQuery [4]
  $myButton.prop('disabled', this.value.length === 0)

}

1:https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2:oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3:https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4:http://api.jquery.com/prop/#prop-propertyName-function

但是,对于可以在整个项目中使用的更全球化的解决方案,我建议使用the textchange jQuery plugin 来获得一个新的、跨浏览器兼容的textchange 事件。它由 the same person 开发,他为 Facebook 的 ReactJS 实现了等效的 onChange 事件,他们几乎将其用于整个网站。我认为可以肯定地说,如果它对 Facebook 来说是一个足够强大的解决方案,那么它可能对你来说也足够强大。 :-)

更新:如果您碰巧需要 Internet Explorer 中的拖放支持等功能,您可能需要查看pandell's more recently updated fork of jquery-splendid-textchange。

【讨论】:

  • 虽然“selectionchange”似乎只在应用于文档时才有效。可以使用“document.activeElement”获取活动元素。
【解决方案5】:

2018,没有 JQUERY

问题是使用 JQuery,仅供参考。

JS

let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
    yourBtnID.style.display = 'none';
    if (textareaID.value.length) {
        yourBtnID.style.display = 'inline-block';
    }
});

HTML

<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>

【讨论】:

  • 这似乎不适用于粘贴事件?感谢您的帮助。
【解决方案6】:

这是另一个(现代)但与前面提到的版本略有不同的版本。用 IE9 测试:

$('#textareaID').on('input change keyup', function () {
  if (this.value.length) {
    // textarea has content
  } else {
    // textarea is empty
  }
});

对于过时的浏览器,您还可以添加selectionchange 和propertychange(如其他答案中所述)。但是selectionchange 在 IE9 中对我不起作用。这就是我添加keyup的原因。

【讨论】:

    【解决方案7】:

    试试这个...

    $("#txtAreaID").bind("keyup", function(event, ui) {                          
    
                  // Write your code here       
     });
    

    【讨论】:

    • 绑定到按键事件是不够的,因为可以通过鼠标更改文本(从上下文菜单中“粘贴”/“剪切”或拖放)。
    【解决方案8】:

    尝试使用 focusout 来做到这一点

    $("textarea").focusout(function() {
       alert('textarea focusout');
    });
    

    【讨论】:

      【解决方案9】:

      .delegate 是唯一一个对我有用的jQuery JavaScript Library v2.1.1

       $(document).delegate('#textareaID','change', function() {
                console.log("change!");
          });
      

      【讨论】:

        【解决方案10】:

        经过一些实验,我想出了这个实现:

        $('.detect-change')
            .on('change cut paste', function(e) {
                console.log("Change detected.");
                contentModified = true;
            })
            .keypress(function(e) {
                if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
                    console.log("Change detected.");
                    contentModified = true;
                }
            });
        

        处理任何类型的输入和选择以及忽略箭头键和 ctrl、cmd、功能键等内容的文本区域的更改。

        注意:我只在 FF 中尝试过这个,因为它是用于 FF 插件的。

        【讨论】:

          【解决方案11】:

          试试这个

           $('textarea').trigger('change');
           $("textarea").bind('cut paste', function(e) { });
          

          【讨论】:

          • 这不是完全错误的。事实上如果将$("#textarea").on('change keyup paste', function() {})和$('textarea').trigger('change');结合起来就可以解决阻止paste自动工作的问题!
          猜你喜欢
          • 1970-01-01
          • 2013-08-29
          • 2011-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多