View Full Version : Use JS to check 2 dropdowns and show div based on that data

06-28-2012, 03:42 PM

Here is my previous post


It's in HTML and CSS section so decided to post my follow up question based on the answear on this JavaScript section.

So how can I get JavaScript to check the values of my 2 options and show right div based on those two?

Lets say I got basic dropdown as described in my previous post and user would choose New York and Los Angeles and the div that has the list would have an ID of "NYC-LOS" or something like that.

How can I use JavaScript to scan the selections and show the right content?

Any help is welcome, just to get me started!


Philip M
06-28-2012, 05:31 PM
How can I use JavaScript to scan the selections and show the right content?

Like this - but you will need a lot of divs to cover all the cities in the USA! And are there not very many (hundreds?) of gas stations between New York and Los Angeles? Surely a driver simply fills up his tank when he needs to. That will depend on the MPG of the car and the speed driven. What use is it to know that there are gas stations hundreds of miles away from where you are now?


<style = "text/css">
.mydivhide {display:none;}
.mydivshow {display:block;}


FROM <select id = "fromcity">
<option value = "NYC" >New York</option>
<option value = "BOS">Boston</option>

TO <select id = "tocity">
<option value = "LOS" >Los Angeles</option>
<option value = "SAN">San Francisco</option>

<input type = "button" value = "Show Info" onclick = "showStuff()">

<div id = "container">
<div id = "NYC-LOS" class = "mydivhide" >Info about New York to Los Angeles</div>
<div id = "NYC-SAN" class = "mydivhide" >Info about New York to San Francisco</div>
<div id = "BOS-LOS" class = "mydivhide" >Info about Boston to Los Angeles</div>
<div id = "BOS-SAN" class = "mydivhide" >Info about Boston to San Francisco</div>

<script type = "text/javascript">

function showStuff() {
var fr = document.getElementById("fromcity").value;
var to = document.getElementById("tocity").value;

var d = document.getElementById('container').getElementsByTagName('div');
var len = d.length;
for (var i = 0; i <len; i++) {
d[i].className = "mydivhide";

var div2show = fr + "-" + to;
document.getElementById(div2show).className = "mydivshow";



My thanks and commiserations to the other contestants, and to you for listening. - Quizmaster, BBC Radio 4

06-28-2012, 06:39 PM
MAny many thanks to you!

I'm not on plannin to do anything even related to USA or gas stations, that example was just the easiest way to demostrate the feature I'm looking for. The thing I'm building is related to Finnish stuff that I can't translate or explain in english so I made up example of something else that I can modify to fit my needs, and this is just perfect!

Respect (Y)