View Full Version : getElementById.addEventListener loop help

08-25-2011, 11:55 PM
I have created this statement and it does its job but not very efficient.

How can I put this in a loop and populate the information that I want anonymously? I do not want to copy and paste this for every (id) there is on this page.

Locate id get value and use same value to change the bgColor of the page

<input id="red" value="red">red
<input id="green" value="green">green

document.getElementById('red').addEventListener('click', function (e) {
inputColor = e.target.getAttribute('value'); document.bgColor = inputColor; }, true);

Your help will be much appreciated! Thanks!

08-26-2011, 12:24 AM
Nevermind... I got it :]

var fm = document.getElementById('form').getElementsByTagName('input');

for (var i=0; i < fm.length; i++)
addEventListener('click', function (e) { inputColor = e.target.getAttribute('value'); document.bgColor = inputColor; }, true);

Old Pedant
08-26-2011, 04:12 AM
Ummm...that seems excessive, to me. What happens if you have a radio button in the same <form> that has a value of, say, "credit". You want to set the background color to "credit"?

On top of that, your code won't work in MSIE 8 or below, because the event is not passed to event handler functions as an argument in those browsers.

But all browsers support the use of this to refer to the object the event handler is attached to.

Finally, document.bgColor is considered obsolescent.

How about this:

function setColorButtons( )
// gets a *collection* of all fields with name "color"
var colors = document.getElementById("theForm").color;
for ( var c = 0; c < colors.length; ++c )
colors[c].onclick = function() { document.style.backgroundColor = this.value; }
<form id="theForm">
<label><input type="checkbox" name="color" value="red"/> Red </label><br/>
<label><input type="checkbox" name="color" value="blue"/> Blue </label><br/>
<label><input type="checkbox" name="color" value="yellow"/> Yellow </label><br/>
<label><input type="checkbox" name="color" value="green"/> Green </label><br/>

<input type="text" name="ThisInputNotSeenInTheLoop" />

If you prefer using text fields for the things to click on, just change to

<input type="text" name="color" readonly="readonly" value="blue" />

et al.