-->

How to set checked attribute to radio in litelemen

2019-08-20 11:34发布

问题:

I would like to know how to set checked to radio button using litelement. I have a object and for each object options, radio button is created.

For example, for id=SG two radio buttons are created, if no checked, set bank as default checked else set corresponding selected radio value as checked.

I got stuck in litelement.

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

回答1:

This sets the checked attribute to true if the option is bank:

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

Looks like you just missed mapping the actual obj (country in my snippet).

Also, in order to change the selected radio, the name should be the same for all radios in a group. Your code is setting a different name to each radio.