'How do I extract data from a json file and assign it to a value in a drop down menu?

I have the following drop down menu and I have coordinating json files;

<option value="2016"> 2016 </option>
<option value="2017"> 2017 </option>
<option value="2018"> 2018 </option>
<option value="2019"> 2019 </option>
<option value="2020"> 2020 </option>

JNorth_Adult_Site_2016_1.geojson
JNorth_Adult_Site_2017_1.geojson
JNorth_Adult_Site_2018_1.geojson
JNorth_Adult_Site_2019_1.geojson
JNorth_Adult_Site_2020_1.geojson

What is the best way to assign the geojson files to the drop down menu. So when someone chooses 2016 on the dropdown, they will get the 2016 results?

I am very new to JS so any help will be very appreciated. Thank you!



Solution 1:[1]

As highlighted in the comments, JS cannot directly read the file system, so I assume your webpage is hosted in server e.g. XAMPP or other alternative, and also your geojson files are kept in the same directory under "files" folder, then you can read the actual required file as you mentioned by using code something like below

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>
    <option value="2016"> 2016 </option>
    <option value="2017"> 2017 </option>
    <option value="2018"> 2018 </option>
    <option value="2019"> 2019 </option>
    <option value="2020"> 2020 </option>
</select>

<script>
    $( document ).ready(function() 
    {
        //The page has been loaded and ready
        $('select').on('change', function() 
        {
            //listen to the select item changes
            $.getJSON( "files/JNorth_Adult_Site_" + $(this).val() + "_1.geojson", function( data ) 
            {
                // If year 2016 is selected file JNorth_Adult_Site_2016_1.geojson will be fetched
                // data variable contains all the content of your actual required file
                console.log(data);
            });
        });
    });
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zain Ul Abidin