1

I'm creating a project and for it to be faster, I have chosen not to use jQuery(I would use only 5% of the full potential of the library).

In this project, I have a <textarea> element, and need to get the contents every time it changes. I have tried different examples, but none worked.

How do I write the following code using Vanilla JavaScript and native DOM Events?

$("#textarea").bind('input propertychange')
// or
$("#textarea").bind('change')
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

4

jQuery .change() is an alias for native change event.

The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.

You can use it fairly simple:

// Non-obtrusive JavaScript example(preffered).    
element.addEventListener('change', callback, false);

// Somewhat obtrusive (not recommended).
element.onchange = function () { ... };

// Obtrusive JavaScript in HTML (not recommended).
<input type="text" onchange="function() { ... };">
halfzebra
  • 6,771
  • 4
  • 32
  • 47
-4

Here's the plain vanilla js way to change content in the DOM.

document.getElementById("textarea").innerHTML = put your new HTML here

Also you probably want to pick a better id than textarea as that's awfully generic.

sunny
  • 3,853
  • 5
  • 32
  • 62