...

View Full Version : Looping through Form Elements?



altergothen
12-13-2010, 04:59 PM
Hi there

I have a form with elements named (& id) 1 through 5
Why can't I loop through all my form elements like this...



function toggle(){
for (var i=1;i<=5;i++)
{
var y = document.getElementById(i);
y.style.backgroundColor = '#FFFFFF';

}
}


The error I get is y is null???
If I hard code the id's like this...
var y = document.getElementById('2');
it works fine??

Please Help

NEWB

abduraooft
12-13-2010, 05:10 PM
var y = document.getElementById(i);
Validate your markup (http://validator.w3.org/#validate_by_input) first. You can't have the value of an id that starts with a number.

Philip M
12-13-2010, 05:14 PM
Form names and ids may not start with a digit.

Try this:-



<form name = "myform">
<input name="Field1" type="text" /><br>
<input name="Field2" type="text" /><br>
<input name="Field3" type="text" /><br>
<input name="Field4" type="text" /><br>
<input name="Field5" type="text" /><br>
<input type = button value = "Change Background Color" onclick = "chk()">
</form>

<script type = "text/javascript">
function chk() {
for(var i=1; i<=5; i++){
document["myform"]["Field" + i].style.backgroundColor = '#FF0000';
}
}
</script>

or if you want to use ids:-


<script type = "text/javascript">
function chk() {
for(var i=1; i<=5; i++){
document.getElementById("Field" + i).style.backgroundColor = '#FF0000';
}
}
</script>




The error I get is y is null???
If I hard code the id's like this...
var y = document.getElementById('2');
it works fine??


Yes it does, because '2' is a string value, not a number. But very srongly advised to avoid.

Nothing's black or white in our country - you're either brilliant or you're hopeless. - Commentator, Radio 5 Live

DrDOS
12-13-2010, 05:16 PM
That's because when you hard code it 2 is a string and not a number. Better to not use numbers as IDs or names, try this:
function toggle(){
for (var i=1;i<=5;i++)
{
var y = document.getElementById("form_item"+i);
y.style.backgroundColor = '#FFFFFF';

}
} where the names and IDs are form_item1, etc., of course you can use any text string you want.

altergothen
12-14-2010, 03:59 PM
Thanks Guys!!!
you have been a great help ;-)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum