Dom Event TextArea Change without Jquery [closed]

守給你的承諾、 提交于 2019-12-08 06:09:33

问题


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')

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/31187103/dom-event-textarea-change-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!