1

I recently downloaded a choropleth map from leafletjs.com. The problem I have is I have multiple js files that are labeled by year (i.e. us-states2012.js, us-states2013.js) and I need to create a drop down menu so that based on the selection from the list (2012, 2013, etc.) the right js file is put into effect.

I am a complete novice and I have no idea how to create the appropriate list function let alone how to call each variable.

Should I place each javascript files into one and sort by name/year (var)? Should I just keep each file separate and call each javascript from the drop down menu? Is any of this possible?

1 Answers1

1

If I'm understanding you correctly I think this should help:

<!DOCTYPE html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script> 
$(document).ready(function(){
$("#select" ).on('change', function() { 
  var year = $(this).val();
  var fileName = "us-states"+year+".js";
  var script = document.createElement('script');
  script.src = fileName;
  $("#head").append(script);
  console.log(script);
  })
});
</script>
</head>
<body>
<select id="select">
  <option value="2014">2014</option>
  <option value="2013">2013</option>
  <option value="2012">2012</option>
  <option value="2011">2011</option>
</select>
</body>
</html>

This is creating an HTML dropdown with years as options. Then, once a selection is made, it's dynamically generating a script with the correct source name by plugging in the year from the dropdown menu.

You'll have to mess with the fileName variable to get it to output exactly what your source url is.

Let me know if this helps or I misunderstood what you're looking for.

Also check out this Stack Overflow post on creating scripts dynamically (I borrowed a couple lines from acrosman's answer).

Community
  • 1
  • 1
cerpintaxt
  • 256
  • 1
  • 2
  • 13