Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.