Create and Attach Event to Button via JavaScript

johns50154917

06-05-2016

Hi Guys,

is there a way to create an event dynamically and attach it to a button?

My idea is basically:

-) Create an event (eg click)

-) add a script node to the event

-) add it to a button

-) force a remerge of the different models

What I tried is to change the type of a existing event and then using remerge() to have in the DOM but that didn't work.

If it is possible to change the event type of an existing event that would also work for me.

best regards,

John

Accepted Solutions (0)

Answers (1)

Answers (1)

tarekahf

21-07-2016

I  have exactly the same requirement.

I was requested to make the Radio Button work like a toggle. If you click on a selected value, then it will clear the selection.

I was able to do that using script with a trick. Basically, I had to use global variable to save the selected value on MouseEnter event for each member of the Radio Button selection, and OnClick event of the Radio Button Selection Group, if the value selected is same as the saved value, then clear the selection.

I am using "savedValue" as a document global variable.

Following is the code:

//Click event of the Radio Button

if (this.rawValue == savedValue.value) {

  this.rawValue = "";

  savedValue.value = "";

} else {

  savedValue.value = this.rawValue;

}

//MouseEnter Event for each of the selection of the radio button

if (savedValue.value !== this.parent.rawValue) {

  savedValue.value = this.parent.rawValue

}

The above code works like a charm !!

Now, what I am trying to do, is to use code with loop to assign the above script to the "click" event and "MouseEnter" event as indicated above. This will save lots of time. I can run this code on the initialize event of the Radio Button required to work like a toggle. Basically, the new function should work as follows:

Input: theElement

Process:

Assign Click Event for theElement to "

if (this.rawValue == savedValue.value) {

  this.rawValue = "";

  savedValue.value = "";

} else {

  savedValue.value = this.rawValue;

}"

Loop over all children of the Radio Button and assign this code to the MouseEnter event:

"if (savedValue.value !== this.parent.rawValue) {

  savedValue.value = this.parent.rawValue

}"

I hope the above is possible.

Tarek