Mike Felder
Mike Felder

Reputation: 139

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

Upvotes: 0

Views: 879

Answers (4)

Karoline Brynildsen
Karoline Brynildsen

Reputation: 3648

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.

Upvotes: 0

mplungjan
mplungjan

Reputation: 177965

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

Upvotes: 0

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31428

Try

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

Upvotes: 0

KooiInc
KooiInc

Reputation: 122906

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

Upvotes: 3

Related Questions