0

Is it possible to detect when a textarea value has been changed with JavaScript?

I know that event listeners for change and input can detect changes that the user makes but I'm trying to detect when the value has been changed programmatically.

Is there any other way to do this?

Example:

var area = document.getElementById('area');

area.addEventListener('input', function(){
  alert();
});

area.value = "hi"; // Shouldn't it fire the alert here?
<textarea id="area"></textarea>
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
  • No, it won't fire because the user didn't input it... – Andrew Li Nov 07 '16 at 05:55
  • initially you can check if text area value is blank or not and if not blank then you can trigger the change event, – Punit Gajjar Nov 07 '16 at 05:57
  • Some code is modifying a textarea, and does so at an unknown time. I want to be able to run some of my own code when that textarea value is altered. If there isn't a way to do that, I'll have to rethink my strategy. – spencer.sm Nov 07 '16 at 06:03
  • 1
    This answer might help http://stackoverflow.com/a/16013352/5788489 – Khorshed Alam Nov 07 '16 at 06:28
  • 1
    Possible duplicate of [Detect programmatic changes on input type text](http://stackoverflow.com/questions/16013024/detect-programmatic-changes-on-input-type-text) – Khorshed Alam Nov 07 '16 at 06:28
  • 1
    @KhorshedAlam Just what I was looking for. Thank you for pointing me there! – spencer.sm Nov 07 '16 at 06:30

2 Answers2

1
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>

<body>
    <textarea>Default value</textarea>

    <script>
            console.log($('textarea').val());
            $('textarea').bind('input propertychange', function() {
                console.log(this.value);
            });
    </script>
</body>

</html>
Pranjal
  • 1,088
  • 1
  • 7
  • 18
  • While this works for when the user changes the text area, it does not call the function if the value is changed through JavaScript. https://jsfiddle.net/xtubwpuv/ – spencer.sm Nov 07 '16 at 06:08
0

in jQuery, you can

$('#area').on('change keyup page', function(){
  alert();
});
  • While this works for when the user changes the text area, it does not call the function if the value is changed through JavaScript. https://jsfiddle.net/nojmkss6/ – spencer.sm Nov 07 '16 at 06:09