如果JavaScript中没有选中复选框,则需要显示警告,我当前的方法不起作用

Need to display alert if no checkboxes are selected in JavaScript, my current method isn't working

本文关键字:警告 不起作用 方法 显示 JavaScript 复选框 如果      更新时间:2023-09-26

我得到一个错误为"对象预期" -错误指向第一个If…从我读到的关于复选框的所有内容(复选框对我不起作用)和我读到的关于多个条件的内容来看,这是对的?即使它不是……

var lucy = window.document.alice
if (lucy.ch1.checked != "true" && lucy.ch2.checked != "true" && lucy.ch3.checked != "true" && lucy.ch4.checked != "true")
{
    alert('Atleast one box must be checked');
}
if (lucy.skeletor.value = "no")
{
    alert('Default Option is not a valid selection.');
}

您不需要lucy.ch1.checked != "true"部分。只要写if (!lucy.ch1.checked && !lucy.ch2.checked && ...)。此外,使用if,而不是If, javascript是区分大小写的。你的代码是失败的保证,所以也许你想把它重写成这样:

var lucy = document.alice; //a form of some kind?
if (!lucy.ch1.checked && !lucy.ch2.checked 
    && !lucy.ch3.checked && !lucy.ch4.checked)
{
  alert('At least one box must be checked');
}
if (lucy.skeletor.value === "no")
{
  alert('Default Option is not a valid selection.');
}

Try

if (!(lucy.ch1.checked || lucy.ch2.checked || lucy.ch3.checked))

Javascript是区分大小写的-你需要使用if()

更新:这是我如何验证表单(我不太可能将对象称为lucy,但这里):

function validate(lucy) {
  if (!lucy.ch1.checked && !lucy.ch2.checked && !lucy.ch3.checked && !lucy.ch4.checked) {
    alert('At least one box must be checked');
    return false;
  }
  if (lucy.skeletor.value = "no") {
    alert('Default Option is not a valid selection.');
    return false;
  }
  return true;
}
<form onsubmit="return validate(this)">

这是因为你有"左右为真。在这种情况下,true不是一个字符串,它是一个布尔值,你可以直接写true。您可以使用KooiInc的答案使其更简单。