如何在litelement中将选中的属性设置为收音机 [英] How to set checked attribute to radio in litelement
问题描述
我想知道如何使用litelement设置选中的单选按钮. 我有一个对象,并为每个对象选项创建了单选按钮.
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.
例如,对于id=SG
,创建了两个单选按钮,
如果未选中,则将库设置为默认选中
否则将选中的相应单选值设置为选中状态.
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.
我陷入了文盲状态.
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
推荐答案
如果选项为bank
,则将checked属性设置为true:
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);
好像您只是错过了映射实际的obj
(我的代码段中的country
).
Looks like you just missed mapping the actual obj
(country
in my snippet).
此外,为了更改选定的无线电,组中的所有无线电的name
应该相同.您的代码为每个电台设置了不同的名称.
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.
这篇关于如何在litelement中将选中的属性设置为收音机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!