You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hilla框架:TypeScript无法获取多组单选按钮值的问题

解决Hilla框架中多组单选按钮选中值的获取问题

方法一:利用Vaadin RadioGroup组件API(推荐)

Vaadin的<vaadin-radio-group>组件自带selectedValue属性,可直接获取对应组的选中值,无需遍历单个单选按钮,这是最贴合Hilla/Vaadin开发规范的实现方式:

submitButton.addEventListener('click', (event) => {
  event.preventDefault();

  // 获取指定name的单选组实例
  const radioGroup1 = document.querySelector('vaadin-radio-group[name="radio1"]') as HTMLVaadinRadioGroupElement;
  const radioGroup2 = document.querySelector('vaadin-radio-group[name="radio2"]') as HTMLVaadinRadioGroupElement;

  // 获取每组的选中值
  const radio1Value = radioGroup1.selectedValue;
  const radio2Value = radioGroup2.selectedValue;

  // 打印日志
  console.log('radio1选中值:', radio1Value);
  console.log('radio2选中值:', radio2Value);

  // 封装数据传递到后端
  const formData = {
    radio1: radio1Value,
    radio2: radio2Value
  };
  // 调用Hilla后端接口,例如:yourBackendService.submitSurvey(formData);
});

方法二:原生DOM遍历方式

如果需要通过遍历单个单选按钮实现,可以按组名分类存储选中值,避免只取第一个选中项:

submitButton.addEventListener('click', (event) => {
  event.preventDefault();

  const selectedValues: { [key: string]: string | undefined } = {};
  // 获取页面所有单选按钮
  const radioButtons = document.querySelectorAll('vaadin-radio-button');

  radioButtons.forEach(radio => {
    if (radio.checked) {
      // 获取当前单选按钮所属组的name
      const groupName = (radio.parentElement as HTMLVaadinRadioGroupElement).name;
      selectedValues[groupName] = radio.value;
    }
  });

  // 打印日志
  console.log('radio1选中值:', selectedValues.radio1);
  console.log('radio2选中值:', selectedValues.radio2);

  // 传递到后端的逻辑
});

注意事项

  • 若使用TypeScript,确保已引入Vaadin组件的类型定义,临时场景可使用any替代HTMLVaadinRadioGroupElement(不推荐长期使用)。
  • 传递到后端时,直接将封装好的formData或selectedValues对象作为参数,调用Hilla自动生成的后端服务接口即可。

内容的提问来源于stack exchange,提问作者Archana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:35:42