Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Div Tag error

Status
Not open for further replies.

countdrak

Programmer
Jun 20, 2003
358
US
<script>
function toggle() {
if( document.getElementById("test").style.display=='none' ){
document.getElementById("test").style.display = '';
}else{
document.getElementById("test").style.display = 'none';
}
}
</script>

I have several <input> boxes and i have the above script to hide and unhide them.

<div id="test" style="display:none;"><input></div>
<div id="test" style="display:none;"><input></div>

I have several of these, but only the first div works. What am I doing wrong. I want all divs to hide and unhide at the same time. Thanks
 
The id attribute must be unique. You can't share the same id in the current document.

You might consider giving them a class name instead...
- use getElementsByTagName('div') to get an array of divs on the page
- iterate over each div and test the arrayOfDivs[loop].className attribute to see if it contains your "special" class
- if it does, then apply your toggle logic to it
- repeat until all divs in the array of divs on the page is checked

Hope that makes some sense (and it'd be so much simpler if we only had getElementsByClassName() available to use natively). Maybe time to look at some Javascript frameworks?

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Thanks a lot, yeah I am looking at prototype. I am trying to find some code to loop over class.
 
Given the following (sample) HTML for your page:
Code:
...
<div class="test"><input /></div>
<div class="test"><input /></div>
<div class="test"><input /></div>
...
You can use the following Javascript code to achieve your solution:
Code:
var divCollection = document.getElementsByTagName('div');
for (var loop=0, max=divCollection.length; loop<max; loop++) {
  var currentNode = divCollection[loop];
  if (currentNode.className == "test") {
    currentNode.style.display = (currentNode.style.display=='none') ? 'block' : 'none';
  }
}

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top