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

StackOverflow https://stackoverflow.com/questions/16972755

  •  31-05-2022
  •  | 
  •  

문제

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);
도움이 되었습니까?

해결책

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

다른 팁

I ended up refactoring the code, replacing MWC.newMessageDefaultOption variable by a callback: a function that selects the default radio button and performs the same followup actions as in the event handler.

Please try below code,

var allRadios = A.all( "input[type='radio']" );
        allRadios.on( 'change', function(e) {
            var portletNamespace='<portlet:namespace/>';
            var selectedRadioButtonValue = e.currentTarget.get('value');
            // add your custom code here
    });

Above code add change event to all radio button and when change event occurs it will execute code inside function.

Please let me know if you need anything more

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top