首页 > 解决方案 > SAPUI5 - 如何获取 RadioGroupButton 的选定按钮索引

问题描述

我是 SAPUI5 的新手,并试图在 SAPUI5 中获取RadioGroupButton的选定按钮索引。

这样做的原因是隐藏或显示更多调查问题。并且表单基于两种语言,因此最好获取索引而不是 selectedButton 的文本。

这是我的 XML 和控制器代码。感谢任何帮助,因为我不明白为什么它无法识别控制台中的按钮索引并显示它未定义!

XML

<VBox class="sapUiMediumMargin">
                        <VBox id="Q1">
                            <Label labelFor="rgb1" text="{i18n>Q1}" />
                            <RadioButtonGroup id="rbg1" columns="2" width="100%">
                                <RadioButton id="RB1-1" text="{i18n>radio.button.no}" select="onSelect"/>
                                <RadioButton id="RB1-2" text="{i18n>radio.button.yes}" select="onSelect"/>
                            </RadioButtonGroup>
                            <!--Small Margin-->
                            <HBox class="sapUiSmallMargin"/>
                        </VBox>

控制器


sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/core/Element",
    "sap/m/MessageToast"
], function(Controller, Element, MessageToast) {
    "use strict";

    return Controller.extend("aaaa.comform.controller.view1", {

        onSelect: function() {

            var oRBGroup = this.getView().byId("rbg1");
            var oButtonSelectedIndex = oRBGroup.getSelectedButtonIndex();
            var oVBox1 = this.getView().byId("Q2"); // another Hidden question to be shown if answer is Yes



            if (oButtonSelectedIndex === 1)) {  // 1 means answer is Yes

                oVBox1.setVisible(true);
                // console.log(getSelctedButton);
            } else {
                oVBox1.setVisible(false);
            }
        }

    });
});

标签: javascriptcontrollersapui5

解决方案


当 select 事件被触发时,您的处理程序将使用 Event 对象调用。您可以在此处阅读事件可用的参数select- https://sapui5.hana.ondemand.com/#/api/sap.m.RadioButtonGroup%23events/select。您可以使用该selectedIndex参数。

首先在 XML 视图中将侦听器移动到 RadioButtonGroup。这将消除为该组中的每个 RadioButton 添加侦听器的需要。

XML

<RadioButtonGroup id="rbg1" columns="2" width="100%" select="onSelect">

控制器

onSelect: function (oEvent) {
  var iIndex = oEvent.gatParameter("selectedIndex"),
      oGroup = oEvent.getSource();

  if (iIndex === 1) {
    ...
  } else {
    ...
  }     
}

推荐阅读