当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Use selectize.js to populate a second dropdown

问题描述:

I have two dropdowns, that the choice of the first dropdown , populates properly the second one.I have successfully implemented it using ajax-php.

Now i am trying to use selectize.js ,applied to the first of the select (the first dropdown) which works fine as expected, but the second dropdown is not populated properly. I have read the documentation (which is not the best i have ever read), and i think that by default selectize.js is not able to handle metadata.

However there is an addOption() and an addItem() method which is what i should implement.My problem is that i can't find a way to parse the results given by ajax-php(and get stored as options in the second dropdown ) and use them properly...

PHP Code

echo "<select name='universities' id='universities' ></select>"; //Here is where the second dropdown is populated properly

JQuery Code-update second dropdown

//Successfully the second dropdown is populated before

$("#universities").selectize();

//If i change the first dropdown option now,the second dropdown remains the same

//if i comment $("#universities").selectize(); line everything works fine.

Any ideas?

网友答案:

Take a look at the sample here: http://brianreavis.github.io/selectize.js/

Look at the City/State example. Key is the .load method. From inside the states dropdown the onChange event has an ajax call that loads the city drop down. The onChange event of the states dropdown is called and the selected value is passed into the function and sent to the url to get the universities. The callback function returns the results that you want loaded into the city dropdown.

   onChange: function(value) {
            if (!value.length) return;
            select_city.disable();
            select_city.clearOptions();
            select_city.load(function(callback) {
                xhr && xhr.abort();
                xhr = $.ajax({
                    url: 'https://jsonp.afeld.me/?url=http://api.sba.gov/geodata/primary_city_links_for_state_of/' + value + '.json',
                    success: function(results) {
                        select_city.enable();
                        callback(results); <--- THIS CALL RETURNS THE JSON RESULTS TO THE CALLER
                    },
                    error: function() {
                        callback(); <--THIS RETURNS TO CALLER ON ERROR 
                    }
                })
            });
分享给朋友:
您可能感兴趣的文章:
随机阅读: