Welcome to WebmasterWorld Guest from 54.205.75.60

Forum Moderators: open

Message Too Old, No Replies

"variable has no properties" error

getElementById dynamic array

   
5:14 pm on Nov 22, 2005 (gmt 0)

10+ Year Member



Can't seem to resolve this problem here. I need to know if a particular button (a variable actually) exists by going through a prepopulated comma separated list of numeric values.
I'm trying to access the properties (e.g. src and value) of an input type image via getElementById using a comma separated string converted into an array.
Below is the part of my code:

my HTML


<input type="image" src="btn_a.gif" name="btn_1" id="btn_1" />
<input type="image" src="btn_a.gif" name="btn_2" id="btn_2" />
<input type="hidden" name="num" id="num" value="1,2,3" />
<img src="spcr.gif" onload="check()" />

my JavaScript

function check(){
var r_num = document.getElementById('num');
var r_num_arr = new Array();
r_num_arr = r_num.value.split(',');

for ( var i = 0; i < r_num_arr.length; i++ ){
alert(r_num_arr[i]);
var num = r_num_arr[i];
var button = document.getElementById('btn_' + num);
button.src = btn_b.gif';
}
}

The interesting thing is that if I use the alert it works - I still get the error "button has no properties" but it works. If i comment out the alert it doesn't work - but i still get the error.

Anyone understand what's going on here?
Please help!

5:21 pm on Nov 22, 2005 (gmt 0)

10+ Year Member



Forgot to mention (perhaps obvious):
as a result of the code each button image (or rsc) should be changed from "btn_a.gif" to "btn_b.gif" if the button name (concatenated adding the variable num) is in the variable r_num (or hidden field "num").

Also just restating (perhaps irrelevant): the hidden field "num" is not prepopulated - it's populated on runtime.

5:33 pm on Nov 22, 2005 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Just a slight modification:


var button = document.getElementById('btn_' + num);
button.src = btn_b.gif';

Change to:


var button = document.getElementById('btn_' + num);
if( button ) button.src = btn_b.gif';
6:54 pm on Nov 22, 2005 (gmt 0)

10+ Year Member



Thank you!
Just as I kept testing with it I realised that if the button does not actually exist then of course it has no properties (dough!)

Thanks again for your help!