telophase: (Near - que?)
telophase ([personal profile] telophase) wrote2011-02-22 05:14 pm

Question for anyone who knows Javascript...

This isn't about a broken script, as I've been able to get it to work. It's about a weird (to me) occurrence in an incrementing variable.

ETA: Solved! It's counting all the divs in the page. Headdesk time!


function showonlyone(thechosenone) {
      var Tab = document.getElementsByTagName("div");
      for(var x=0; x<Tab.length; x++) {
      	name = Tab[x].getAttribute("name");
      	if (name == 'Tab') {
        	if (Tab[x].id == thechosenone) {
				Tab[x].style.display = 'block';
				//alert('Boo - Tab' + x);
            } else {
            	Tab[x].style.display = 'none';
				//alert('Wah - Tab' + x);
            }
        }
      }
}


See, the variable x above? It iterates through three divs, so that I can switch between them and change the display status when someone chooses an option from a drop-down menu. (Er, no comments about whether the drop-down is a good idea or not: it was told to me to do. :D)

Anyway, x is showing up as 10, 11, and 12, instead of 0, 1, and 2 as I'd expect. I ended up having to name the divs Tab10, Tab11, and Tab12 to make it work. So while it's not a serious problem, it is a perplexing one.

Ideas? Explanations?
foxfirefey: A guy looking ridiculous by doing a fashionable posing with a mouse, slinging the cord over his shoulders. (geek)

[personal profile] foxfirefey 2011-02-22 11:30 pm (UTC)(link)
(Also, sorry about the error, but I think DW and LJ have put in some anti-malware scripting and I haven't figured out how to properly display Javascript without triggering it. The pre tag doesn't seem to work.)

All you'll need to do is in your code, replace < and > with &lt; and &gt; -- I usually do it in a text editor that has find a replace. Otherwise it can confuse the entry cleaner that's trying to figure out what HTML is where so that it can try and do things like, yes, clear out malware, or make sure someone's un-closed div doesn't wreck reading pages.

[identity profile] jarodrussell.livejournal.com 2011-02-22 11:25 pm (UTC)(link)
Obvious question is obvious: how many DIV tags are in the page?

[identity profile] badtzphoto.livejournal.com 2011-02-23 06:13 am (UTC)(link)
It's puzzling. Could there be a global x that has 10 as a value? In theory, that variable x should be local but with javascript it's hard to say. What happens if you change x to i or something else?

[identity profile] telophase.livejournal.com 2011-02-23 03:16 pm (UTC)(link)
A-ha! Yes, obvious question is obvious answer. Thank you!

[identity profile] telophase.livejournal.com 2011-02-23 03:17 pm (UTC)(link)
[livejournal.com profile] jarodrussell nailed it: it's counting all the divs on the page, not just the ones in the switcheroo section. And now I'm headdesking.