Checkbox toggle

Can’t seem to create a select toggle. When checkbox is checked enable button, when checkbox is unchecked disable button. I need it to work with the for loops though. The first for loops runs the code properly.


function selectone () {
	var message = document.getElementById('pm');
	
	for (var i = 0; i < message.length; i++)
	{
		if(message[i].checked !== checked)
		{
			document.getElementById('multiple_action').disabled = true;
			document.getElementById('drop_button').setAttribute("class", "drop_button disabled");
		}
	}
	for (var i = 0; i < message.length; i++)
	{
		if(message[i].checked == checked)
		{
			document.getElementById('multiple_action').disabled = false;
			document.getElementById('drop_button').setAttribute("class", "drop_button");
		}
	}
}

There are a number of flaws with this. The main one is that getElementById can by its very nature only give you a single DOM element. Therefore a for loop is pointless, because it will be looping over a single element.

The second flaw is that your two loops are identical, therefore you should combine them into one.

Finally, you are doing a comparison against a variable called checked, which has not been defined anywhere.

If #pm was the single checkbox, you could do this:

var chk = document.getElementById('chk').checked;
document.getElementById('multiple_action').disabled = !chk;
document.getElementById('drop_button').className = chk ? 'drop_button disabled' : 'drop_button';

I actually got the function to work using this code. I imagine it still has inefficiencies. I don’t know how to combine the loops. When I try to, they break on me.

function selectone () {
var message = document.getElementById(‘pm’);

for (var i = 0; i &lt; message.length; i++)
{
	if (message[i].checked == false)
	{
		document.getElementById('multiple_action').disabled = true;
		document.getElementById('drop_button').setAttribute("class", "drop_button disabled");
	}
}
for (var i = 0; i &lt; message.length; i++)
{
	if (message[i].checked == true)
	{
		document.getElementById('multiple_action').disabled = false;
		document.getElementById('drop_button').setAttribute("class", "drop_button");
	}
}

}

You haven’t addressed the main flaw I pointed out. That’s the most important thing. Posting some HTML would help (but use the syntax highlighting).