Chained Select with NO jQuery or Ajax

一个人想着一个人 提交于 2019-12-01 11:56:54

问题


I'm using XAMPP Lite - USB Version and found that the jQuery chained select boxes scripts don't work because they rely on AJAX which is not working on my XAMPP.

I have two Select boxes:

<label>Province</label>
<select name="province"> 
<option value="ontario">Ontario</option>
<option value="quebec">Quebec</option>
<option value="novascotia">Nova Scotia</option>
</select> 

<label>city</label>
<select name="city"> 
</select> 

I need to be able to select a province and load different cities into the "city" name select. I have to do this without jQuery or Ajax. FYI It does not matter how long the javascript array variables have to be which will hold all the data. I just need someone to start me out with the script please.


回答1:


here's a quick sample, not optimized but does the job. as said, no jQuery and no AJAX. this one works in standards compliant browsers, you man need to tweak it for IE coz i have no IE to test on.

<label>Province</label>
<select id="province"> 
    <option value="p1">p1</option>
    <option value="p2">p2</option>
    <option value="p3">p3</option>
</select> 

<label>city</label>
    <select id="city"> 
</select> ​


window.onload = (function() {

    var locations = {
        'p1': [
            'p1c1',
            'p1c2',
            'p1c3',
            ],
        'p2': [
            'p2c1',
            'p2c2',
            'p2c3',
            ],
        'p3': [
            'p3c1',
            'p3c2',
            'p3c3',
            ],
    };

    var provinces = document.getElementById('province');
    var cities = document.getElementById('city');

    provinces.addEventListener('change', function() {
        loadCities(this.value)
    }, false)


    var loadCities = (function loadCitiesFunc(key) {
        key = key || 'p1';
        var docFragment = document.createElement('select');
        for (var i = 0; i < locations[key].length; i++) {
            docFragment.appendChild(new Option(locations[key][i], locations[key][i]));
        }
        cities.innerHTML = docFragment.innerHTML;

        return loadCitiesFunc;
    }())

}());​


来源:https://stackoverflow.com/questions/9917577/chained-select-with-no-jquery-or-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!