如何在litelement中将checked属性设置为radio

问题描述 投票:0回答:1

我想知道如何使用litelement将checked设置为单选按钮。我有一个对象,对于每个对象选项,都会创建单选按钮。

例如,对于id=SG,将创建两个单选按钮,如果未选中,则将bank设置为默认选中,否则将相应的所选无线电值设置为已选中。

我被困在文字中。

const obj= [{
    id: "SG",
    options: ["bank", "credit"]
  },
  {
    id: "TH",
    options: ["bank"]
  }
];
render(){
  ${obj.map((e)=>{
return html`
         <form>
            ${obj.options.map((option_value)=>{
                   return html`
                       <input class="form-check-input"  name="sending-${option_value}" type="radio" id="provider-send-${option_value}" value=${option_value} ?checked=${option_value=="bank"} > // not working
                         <label class="form-check-label">
                                ${option_value}
                         </label><br>
             `})}
          </form>
   })`;

}
Expected Output:
Set checked to corresponding radio selected
If no checked, set bank as default checked
javascript jquery polymer lit-element lit-html
1个回答
0
投票

如果选项为bank,则将checked属性设置为true:

import { LitElement, html } from 'lit-element';

class TestElement extends LitElement {
  static get properties() {
    return {
      countries: {
        type: Array,
      },
    };
  }

  constructor() {
    super();
    this.countries = [
      {
        id: 'SG',
        options: ['bank', 'credit'],
      },
      {
        id: 'TH',
        options: ['bank'],
      },
      {
        id: 'MY',
        options: ['credit'],
      }
    ];
  }

  render() {
    return html`
      ${this.countries.map(country => html`
        <fieldset>
          <legend>${country.id}</legend>
          <form>
            ${country.options.map(option => html`
              <input
                id="provider-send-${option}"
                name="sending-${country.id}"
                type="radio"
                class="form-check-input"
                value="${option}"
                ?checked=${option === 'bank'}
              >
              <label class="form-check-label">${option}</label>
              <br>
            `)}
          </form>
        </fieldset>
      `)}
    `;
  }
}

customElements.define('test-element', TestElement);

看起来你只是错过了映射实际的obj(我的片段中的country)。

此外,为了更改所选的无线电,对于组中的所有无线电,name应该相同。您的代码为每个收音机设置了不同的名称。

© www.soinside.com 2019 - 2024. All rights reserved.