Jump to content

simple "check whether checkbox is checked and do something" not working


RLJ

Recommended Posts

Hi, probably a very straightforward problem, but here it is:

 

<html>

<head>
<script language='JavaScript'>

function enable3(moreoptions)
{
    var elements = document.getElementsByName("txt");
    var length = elements.length;

    for (var i = 0; i < length; i++)
    {
//if(document.getElementById(moreoptions).checked == true)        
	{elements[i].style.color='red';}
//else	
	//{elements[i].style.color='blue';}
    }
}
</script>
</head>


<body>

<label for="moreoptions"><input type="checkbox" name="moreoptions" id="moreoptions" onchange="enable3(moreoptions)"> Show additional options</label><p></p>

<span id ="span1" name="txt">SPAN1</span>
<span id ="span2" name="txt">SPAN2</span>
<span id ="span3" name="txt">SPAN3</span>

</body>
</html>

 

I want to use the above code - when checkbox 'moreoptions' is clicked - to check whether the checkbox is checked or not and, depending on the result, make elements with name 'txt' either blue or red.

 

With parts of the code commented out, as above, it works fine and turns the elements red when the checkbox is clicked. However, when those parts are not commented out (i.e. the checking whether the checkbox is checked or not part is enabled), the elements with name 'txt' don't change color.

 

Can someone see where I've gone wrong??

 

Much appreciated! Thanks.

Here's a working example http://gonavygolf.com/test8.html. View the source to see the code.

Use onclick instead of onchange. Pass 'this' to the onclick function. There's no need for the {} when referencing

the elements array.

Cheers for the reply.

 

However, your link's not working, 404 page not found.

 

Also, since I have a label for the checkbox, isn't onchange better than onclick? Because the checkbox can change even if it is not directly clicked on.

 

Thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.