gpt4 book ai didi

javascript - 如何检查是否至少选择了 4 个列表框中的 1 个项目

转载 作者:行者123 更新时间:2023-12-02 19:14:48 26 4
gpt4 key购买 nike

我正在尝试为多选列表框编写一个JS验证函数。

我有 4 个多选列表框,我需要检查用户是否已从至少一个列表框值中进行选择。也就是说,在 4 个列表框中,用户应从至少 1 个列表框中进行选择(任意数量的值)。

这是我正在编写的函数,

function validate(form)
{
if ((document.getElementById("A").value=='') || (document.getElementById("B").value=='') || (document.getElementById("C").value=='') || (document.getElementById("D").value==''))
{
if (0 < message.length) { message += "\n"; }
message += "You must select atleast one of the listbox items ";

}
}

我知道问题出在 OR 条件上。除非从这些列表框中的每个中选择 1 个值,否则不允许保存表单。

但我需要检查是否应选择4 个列表框中的至少 1 个(任意数量的项目)。

我该怎么做?

最佳答案

您需要更改为使用 AND 条件,这将是适当的悲伤路径方法:

if (document.getElementById("A").value == '' && 
document.getElementById("B").value == '' &&
document.getElementById("C").value == '' &&
document.getElementById("D").value == '') {

//then they didn't select AT LEAST ONE item
}
else {
//they did pick at least one
}

编辑:

您可以通过执行以下操作来采用快乐路径方法:

 if (document.getElementById("A").value !='' || 
document.getElementById("B").value !='' ||
document.getElementById("C").value !='' ||
document.getElementById("D").value !='') {

//then they did select AT LEAST ONE item
}
else {
//they didn't pick at least one
}

关于javascript - 如何检查是否至少选择了 4 个列表框中的 1 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com