Search code examples
liferayliferay-6alloy-ui

In AlloyUI (or YUI3 I suppose), how do I trigger a change event when checking a radio button using setAttribute?


Changing the value of a radioButton using setAttribute('checked',true) changes the value of the radio button, but does not fire a change event.

This does not seem to be limited to YUI or AlloyUI (see for instance Detecting a change in radio button/checkbox state).

To work around that issue, I would like to programmatically fire a change event when I set the value of my radio button.

How can I do that in Alloy UI (I am using Liferay 6.1 GA2) ?

Thanks Alain

Some specifics:

the html:

<aui:input type="radio" label="${viewMenuItem.label}" value="${viewMenuItem.value}"
   id="${messageWallDisplay.newMessageOptionName}${viewMenuItem.value}"
   name="${messageWallDisplay.newMessageOptionName}" data="${viewMenuItem.dataMap}"
   checked="${viewMenuItem.value == messageWallDisplay.newMessageOptionDefaultValue}"/>

the event delegation setup (I also tried event callback on the radiobuttons):

  messageTypeRadioGroup.delegate('change', function (event){
     var option = event.currentTarget;
     if (option.get("checked")==true){
        showHideUserSelection(option);
     }
  }, 'input[type=radio]');

The setAttribute that doesn't trigger the change event:

MWC.newMessageDefaultOption.setAttribute('checked',true);

Solution

  • This answer here looks like what you're trying to accomplish: Javascript: simulate a click on a link

    If MWC.newMessageDefaultOption is your radio node, you can just do something like this:

    MWC.newMessageDefaultOption.simulate('change');
    

    As noted in the comment Simulate is for testing purposes. For best practice:

    var doThingsOnChangeFunc = function(arg1, arg2) {
        // do things!
    }
    
    myNode.on(
        'change',
        function(event) {
            var arg1 = event.currentTarget;
            var arg2 = "something";
    
            doThingsOnChange(arg1, arg2);
        }
    );
    

    Then later down when you are programmatically changing your radio button\checkbox:

    myNode.setAttribute('checked', true);
    
    doThingsOnChange(arg1, arg2);