Reputation: 3
I'm trying to make a Christmas List page on my Family website, and I would like it to have a drop-down list of everyone who has a list, and when you click someone's name, it shows their list. I was thinking something using display: none, and display: block. But I'm not really sure how to go about it, I've never really done this sort of thing.
If anyone posts a solution, I would prefer it to not be JQuery, as I don't really understand it. But, it's just a preference, any help is greatly appreciated.
Upvotes: 0
Views: 59
Reputation: 65855
You've got the right idea. There are many ways to do this, but here's a way to show the right list and hide all the others.
// Get references to the elements in question
var people = document.getElementById("people");
// Get all the lists in a collection and convert that collection to an Array
var allLists = Array.prototype.slice.call(document.querySelectorAll(".list"));
// Set up a change event handler on the drop down list
// so that when the selection in the drop down changes,
// the associated function will execute
people.addEventListener("change", function(){
// Store the currently selected person
var person = this.value;
// Loop through all the lists and show the matching one and hide all the others
allLists.forEach(function(list){
if(person === list.id){
list.classList.remove("hidden");
} else {
list.classList.add("hidden");
}
});
});
/* Set all lists to be hidden by default */
.hidden.list { display:none; }
<select id="people">
<option value="">--- Choose A Person ---</option>
<option value="tom">Tom</option>
<option value="mary">Mary</option>
<option value="sue">Sue</option>
</select>
<div id="tom" class="hidden list">
<h1>Tom's List</h1>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
<div id="mary" class="hidden list">
<h1>Mary's List</h1>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
<div id="sue" class="hidden list">
<h1>Sue's List</h1>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
Upvotes: 1
Reputation: 15754
Assuming this is your HTML:
<select id ="ddl" name="ddl" onchange="ShowList(this.value);">
<option value='1'>Mom</option>
<option value='2'>Dad</option>
<option value='3'>Brother</option>
</select>
Javascript:
function ShowList(id) {
// based on your id, show section so something like if id == 1 show Mom's div
}
You could of course pass the name to the function instead, so you'd pass "Mom" to your function and based off that show the "MomDiv" for example. I'll leave it to you to figure out the rest.
Upvotes: 0