Programing

jQuery에서 텍스트 영역의 변경 이벤트에 어떻게 바인딩 할 수 있습니까?

lottogame 2020. 5. 1. 08:00
반응형

jQuery에서 텍스트 영역의 변경 이벤트에 어떻게 바인딩 할 수 있습니까?


변경 사항이 있으면 캡처하고 싶습니다 <textarea>. 문자 (삭제, 백 스페이스)를 입력하거나 마우스를 클릭하여 붙여 넣기 또는 잘라 내기하는 것과 같습니다. 모든 해당 이벤트를 트리거 할 수있는 jQuery 이벤트가 있습니까?

변경 이벤트를 시도했지만 구성 요소에서 탭 아웃 한 후에 만 ​​콜백을 트리거합니다.

사용 : <textarea>텍스트 포함되어 있으면 버튼을 활성화하고 싶습니다 .


실제로 이것을 시도하십시오 :

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

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

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

데모

변경, 타이핑, 자르기, 붙여 넣기 등 모든 변경 사항에 적용됩니다.


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 데모


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();
  }
});

This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):

// 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

BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange event. It was developed by the same person who implemented the equivalent onChange event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)

UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell's more recently updated fork of jquery-splendid-textchange.


2018, without JQUERY

The question is with JQuery, it's just FYI.

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>

Here's another (modern) but slightly different version than the ones mentioned before. Tested with IE9:

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

For outdated browsers you might also add selectionchange and propertychange (as mentioned in other answers). But selectionchange didn't work for me in IE9. That's why I added keyup.


Try to do it with focusout

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

try this ...

$("#txtAreaID").bind("keyup", function(event, ui) {                          

              // Write your code here       
 });

.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1

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

After some experimentation I came up with this implementation:

$('.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;
        }
    });

Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.

Note: I've only tried this in FF since it's for a FF add-on.


Try this

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

참고URL : https://stackoverflow.com/questions/11338592/how-can-i-bind-to-the-change-event-of-a-textarea-in-jquery

반응형