Search code examples
javascriptsapui5

SAPUi5 Radio Button Selected Text


I have a radio button in my XMLview as shown below. The data is bound from the model. My requirement is to validate the radio buttons after the data binding. Below is my controller code. i am trying to read the value of the selectedButton text in my controllers AfterRendering method.

XML View:

<RadioButtonGroup id="rbgtype" > 
<RadioButton text="Yes" selected="{/rbgtype}"/> 
<RadioButton text="No" selected="{=!${/rbgtype}}"/> </RadioButtonGroup>

Controller

onAfterRendering: function () { 
var that = this; console.log("rbgtype"+that.getView().byId("rbgtype").getSelectedButton().getText());} 

Strangely I am always getting the value "Yes" , irrespective of selected value. Can some one advise where I am doing wrong please.


Solution

  • It does that because the RadioButtonGroup doesn't initially have a property set selectedIndex. It seems to fail the getSelectedButton method whenever selectedIndex isn't set.

    Maybe you can work around this issue like this? Hope this helps.

    View

            <RadioButtonGroup id="rbgtype" selectedIndex ="{/rbgtype}">
                <RadioButton text="Yes" />
                <RadioButton text="No"/>
            </RadioButtonGroup>
    

    Controller

            onInit: function() {
            var type = false;
            var oModel = new JSONModel({
                rbgtype: type ? 0 : 1
            });
    
            this.getView().setModel(oModel);
        },
    
        onAfterRendering: function() {
            sap.m.MessageToast.show("rbgtype: " + this.byId("rbgtype").getSelectedButton().getText());
        },
    

    VIEW 2

    <RadioButtonGroup id="rbgtype" selectedIndex ="{= ${rbgtype} ? 0 : 1 }">
                <RadioButton text="Yes" />
                <RadioButton text="No"/>
    </RadioButtonGroup>