quoque
quoque

Reputation: 11

Display another text when CheckBox is (un)checked

It should be quite simple. You have the following text:

Your scream: Whoops!

And when you check the checkbox below that says

Scream "yay" instead!

the word “Whoops!” should change to “Yay!”:

Your scream: Yay!

So my body is (I want to do it with a function):

Your scream: <script>GiveMeSomeScream()</script>!<hr>
<input type="checkbox" name="whatever" id="ScreamYay"> Scream "yay" instead!

But I’m having problems with the actual script. Here’s what I tried first:

function GiveMeSomeScream()
{  if (document.GetElementById('ScreamYay').checked == "true")
{  document.write("Yay");
}  else
{  document.write("Whoops");
}}

But it just wouldn’t work. So I expanded it like this:

var yay = document.getElementById('ScreamYay').checked
function GiveMeSomeScream()
{  if (yay == "true")
{  document.write("Yay");
}  else
{  document.write("Whoops");
}}

Now it gives “Whoops” every time (even if I make the checkbox checked defaultly), and that’s pretty much it.

I know it’s ridiculous I can’t even handle a checkbox, but still I would be glad for any help.

Upvotes: 1

Views: 74

Answers (3)

Iw As
Iw As

Reputation: 41

You can do it like following
you have to add onchange function on checkbox tag.
also document.GetElementById is wrong
document.getElementbyId is right
finally
document.getElementById("ScreamYay").checked == "true" is wrong
document.getElementById("ScreamYay").checked == true is right

function GiveMeSomeScream()
{  if (document.getElementById('ScreamYay').checked == true)
{  document.write("Yay");
}  else
{  document.write("Whoops");
}}

Upvotes: 0

BBQ Singular
BBQ Singular

Reputation: 467

The value returned from document.getElementById('elementID').checked will be a boolean. This is further explained here. To use that, you can simply test against the value using if(yay === true) or if(yay) as @Alex suggests. As for using document.write, you need to include the html tags (markup) like this.

Upvotes: 0

Alex
Alex

Reputation: 842

Change if (yay == "true") to if (yay)

Upvotes: 1

Related Questions