简体   繁体   中英

How to input data to jsfiddle dropdown from an Excel Sheet or .csv file?

I have a requirement where I can use JS Fiddle dropdown to populate States and Cities. I have data in an excel sheet like this

State           City
Andhra Pradesh  Kadapa
Andhra Pradesh  Kadiri
Andhra Pradesh  Kagaznagar
Andhra Pradesh  Kakinada
Andhra Pradesh  Kalyandurg
Andhra Pradesh  Kamareddy
Assam           Karimganj
Assam           Kokrajhar
Bihar           Katihar
Bihar           Kanti
Bihar           Kishanganj
Bihar           Khagaria
Bihar           Kharagpur
Chhattisgarh    Kawardha
Chhattisgarh    Kanker
Chhattisgarh    Korba
Chhattisgarh    Kondagaon
Gujarat         Kapadvanj
Gujarat         Karjan
Gujarat         Kalavad
Gujarat         Kadi
Gujarat         Kalol
Haryana         Karnal
Haryana         Kalan Wali
Haryana         Kaithal

and the js fiddle for populating dropdown is as follows

--from here I want to input data from excel sheet or CSV or any other better suggestions in place of following code.
var data = [ // The data
    ['ten', [
        'select','eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];
--up to here.-----------------------------------

and now I want to pass the data to the below function

$a = $('#State'); // The dropdowns
$b = $('#City');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][3]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

and here are the dropdowns

<select id=state></select></br>
<select id=city></select>

My concern is how to

Convert the file into JSON data for easy access -- the data shouldn't change very often, so this shouldn't be a problem. You can then load this via AJAX :

$.getJSON('ajax/cities.json', function(data) {
    var $opt = $("<option>")
       .attr("value",data.city)
       .text(data.state);
    $('#state').append($opt);
});

...or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM