使用带有多组选项的disabled属性来限制苗条表单中复选框的数量



显示项选项的表单。用户应该为每个项目选择特定数量的选项。选项的例子:

let optiongroups = [
{
groupname : "exactly1",
grouplimit : 1,
id : 123,
optionitems : [
{
name : "One",
price : 1
},
{
name : "Two",
price : 2
},
{
name : "Three",
price : 3
},
{
name : "Four",
price : 4
}
]
}

)

使用一组选项,这段代码可以工作:

<form name="optionsform" on:submit|preventDefault={()=>collectoptions(itemid, itemprice, itemname,  itemdescription, variationname, variationprice)}>
{#each optiongroups as group}
<div style="margin : 5px; border : solid green;">
<li style="list-style : none;">
{group.groupname} - {group.grouplimit}
{#each group.optionitems as option}
<li>
<label>
<input name={group.groupname}  type="checkbox" bind:group={checkresults} value={[{"name" : option.name},{ "price" : option.price } ]} on:click={(e)=>{handleclick(e, group.groupname, group.grouplimit, group.id)}} disabled={disableit === true}>
{option.name} : {option.price}
</label>

</li>
{/each}
</li>
</div>
{/each}
<button type="submit" >Add To cart</button>
</form>

通过在我的脚本中使用disabled来禁用输入复选框,它确实可以正常工作,但当我添加多于一组选项时-它来自数据库,我不知道每个项目有多少选项组-所以当我添加多于一组选项时:

let optiongroups = [
{
groupname : "exactly1",
grouplimit : 1,
id : 123,
optionitems : [
{
name : "One",
price : 1
},
{
name : "Two",
price : 2
},
{
name : "Three",
price : 3
},
{
name : "Four",
price : 4
}
]
},
{
groupname : "exactly2",
grouplimit : 2,
id : 369,
optionitems : [
{
name : "2-One",
price : 22
},
{
name : "2-Two",
price : 44
},
{
name : "2-Three",
price : 66
},
{
name : "2-Four",
price : 88
}
]
}]

如果您在repl中运行此代码,您将观察到,当您单击第一组中的选项(exactly1)并且超过需要选择的选项限制时,该组中的其余复选框被禁用-这是期望的结果-但是当您开始在第二组中进行选择时- exactly2 -您将选择一个复选框,然后所有其余的复选框也被禁用。我试着用不同的方式移动limit变量,但没有什么能阻止第二组也被禁用。

禁用行,我尝试添加不同的条件,如:

disabled={disableit === true && checkresults['id'].includes(group['id'])}

但是,它仍然禁用了第二组中的其余复选框。因此,用户可以从两组中总共选择3个复选框,而不是从第一组中选择1个选项,从第二组中选择2个选项。

想知道是否有人能找出哪里是错误或指导我如何包括一组以上的选项,让用户从每组中选择正确的选项数量,然后限制复选框的其余部分。

不能为所有组使用简单的全局值disableit;相反,您需要按组检查状态。例如,如果checkresults根据可用组初始化为字典,如下所示:

let checkresults = Object.fromEntries(optiongroups.map(g => [g.groupname, []]));

你可以通过:

<input name={group.groupname}  type="checkbox"
bind:group={checkresults[group.groupname]}
value={[{ "name" : option.name }, { "price" : option.price }]}
disabled={
checkresults[group.groupname].length === group.grouplimit &&
checkresults[group.groupname].some(x => x[0].name == option.name) == false
}>

REPL例子

value设置的方式使得这有点冗长。此外,将每个组的整个内容隔离到一个单独的组件中会更容易,这样它们就可以在本地管理自己的状态,并且您不需要一直使用像checkresults[group.groupname]这样复杂的状态访问。

单独组件的例子

最新更新