Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

How to fire change event of HTML element text using Javascript, in a Chrome Extension?

I'm creating an chrome extension, and having issue that even if I changed the element text, the submit button not enables as usual and other stuff is not processing as manual typing.

I'm trying to fire the text changed event to process the elements normal behavior of manual typing using following script;

var el2=document.getElementById("tmsg");
el2.innerText="hello world";
try{                                     
    el2.fireEvent("onchange");
}catch(error)
{
   alert("err:"+error);
}

However, the text is set, but getting following error

TypeError: el2.fireEvent is not a function

I'm looking for solution with java script, without JQuery solutions, but none worked for me.

Can anyone please point me what I'm doing wrong here, or better way to do that?

question from:https://stackoverflow.com/questions/65642231/how-to-fire-change-event-of-html-element-text-using-javascript-in-a-chrome-exte

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are getting that error because eventTarget.fireEvent() is a proprietary method used in Internet Explorer.

The modern and standard way to manually dispatch events, according to MDN is as follows:

// CREATE EVENT
const event = new Event('change', {bubbles: true});

// GET TARGET ELEMENT
const el2 = document.getElementById('tmsg');

// DISPATCH EVENT
el2.dispatchEvent(event);

Hope it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...