Wednesday 16 July 2014

Fire javascript events manually!!!

Hi All,

In this post, I am going to explain how I fired javascript events of my webpage manually. I came across number of posts, when I googled about it.

But the solution, I am going to explain below is the most simplest one and I am unable to find further reference related to how this feature works.

Anyway, I am documenting my findings here. Once, I come across more info - I will update this post.

Lets get into the scenario:

I want to fire 'onchange' event in one of my field. But I need to change the value of the corresponding field using javascript - hence 'onchange' event will not get triggered.

So, I was looking for javascript that would trigger the 'onchange' event and I found the simple solution as below:

var sel1 = document.getElementById('testID');
sel1.value='testdata';
sel1['onchange'](sel1);

As you can observe, I am just getting the reference of the my element and updating the value of it.

Then with a single line code, I am triggering the 'onchange' event. It is as simple as that and we are done. Event will get triggered!!!

Below post elaborates this concept in bit detail. You can refer this for your reference:

http://www.guahanweb.com/2010/03/02/how-to-manually-trigger-events-in-javascript/

I used above mentioned code in Firefox and Chrome. It worked. I am not sure about older version of IE. But, I hope it should work in IE10+ version.

No comments:

Post a Comment