Open / close div tag based on menu selection, not working

Hello,
The script is below for your review. I’m trying to open and close the div tags based on the menu selections. for testing purpose it only setup to close the div tag. the current script on closes the first div tag and the rest does nothing… not sure what im doing. any help you can provide would be greatly appreciated. thank you.

This script pulls in menu values from db for display.
example menu: Add New Member1 | Modify Existing Member2 | Member Lookup3

<ul class="navH_memberUpdate" >			
	<?php 
		foreach($get_navManageMemberListing as $manageList) { 
			echo '<li value="'.$manageList['mgn_index'].'" id="test1" > <a href="#" >'.$manageList['mgn_manageMember'].$manageList['mgn_index'].'</a></li>'; 
					}  
					
	?>						
</ul>

<!--   looking to have the div tags open/close based on the menu selection  -->
		<div id="ID_modifyDIV1" >
			<h3>Div 1</h3>	
			<div style="border: 1px solid green">new user</div>
		</div>
		<br>

		<div id="ID_modifyDIV2" >
			<h3>Div 2</h3>	
			<div style="border: 1px solid green">Modify user</div>
		</div>
		<br>

		<div id="ID_modifyDIV3" >
			<h3>Div 3</h3>	
			<div style="border: 1px solid green">Lookup</div>
		</div>
		<br>

JavaScript component, for now it only closes the div tag (testing)

$(document).ready(function() {  
	$("#test1").click(function(event) {
		event.preventDefault();		
		 var testX = document.getElementById("test1").value;

		if(testX ==1) {
			document.getElementById("ID_modifyDIV1").style.display = "none"; 
		}
		if(testX == 2) {
			document.getElementById("ID_modifyDIV2").style.display = "none"; 
		}	
		if(testX == 3) {
			document.getElementById("ID_modifyDIV3").style.display = "none"; 
		}	
	});
}); 

Hi @robin01, you’d select the menu items via a common class then, rather than only a specific one by its ID; inside the event handler, the event.target will then be the element that was clicked.

Also note that list items don’t have a value attribute; instead, you could reference the related divs directly using an actual href attribute:

<ul>
  <li class="menu-item"><a href="#item-1">foo</a></li>
  <li class="menu-item"><a href="#item-2">bar</a></li>
  <li class="menu-item"><a href="#item-3">baz</a></li>
</ul>

<div class="content-item" id="item-1">foo content</div>
<div class="content-item" id="item-2">bar content</div>
<div class="content-item" id="item-3">baz content</div>
var $contentItems = $('.content-item')

$('.menu-item').click(function (event) {
  event.preventDefault()
  $contentItems.hide().filter(event.target.hash).show()
})

Actually, you don’t even need JS for this though – the same can be achieved using CSS only:

.content-item {
  display: none;
}

.content-item:target {
  display: block;
}

Hi M3g4p0p,

Thanks for the code, it worked great… thank you.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.