开发者

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

I'm getting an error for "Object Expected" - the error points to the first If... from everything I read about checkboxes (checkboxes never work for me) and what I read about multip开发者_如何学JAVAle conditionals, this is right? Even though it isn't...

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.');
}


You don't need the lucy.ch1.checked != "true" part. Just say if (!lucy.ch1.checked && !lucy.ch2.checked && ...). Furthermore use if, not If, javascript is case sensitive. Your code is a guarantee for failure, so maybe you want it to rewrite it to something like:

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 is case sensitive - you need to use if()

Update: here is a how I would validate a form (I would not likely call the obejct lucy, but here you go):

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


It's because you have "" around true. In this case true is not a string, it's a boolean value, and you can just write true in stead. You can make it even more simple by useing KooiInc's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜