Reputation: 11
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
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
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