The principle of the dynamic Drop-down list is actually very simple, when a pull list triggers the onchange event, and then use Ajax in the background to the server asynchronously request data, and finally the server returned to the data after parsing dynamically added to the designated select on it!
First look at the background data output, we assume that the server sent to the customer segment of the JSON data format is as follows:
{
"Options": [
{' Value ': value, ' Text ': text},
{' Value ': value, ' Text ': text},
{' Value ': value, ' Text ': text}
]
}
Where the options is the identifier of the entire JSON object, an array that represents option in a select, and of course the value is an object, with two attributes, one value, one text, Corresponds to the value in option and the text value displayed respectively.
With the data format, it is much easier to communicate with the client and server side. Let's write the client's JS method first. Here I am providing a static utility class Select, specifically for the Select element's operation method, as follows:
A practical Select class for select operations
function Select () {};
Generates the options item for the specified select, based on the specified JSON object (clear the original options).
Select.create = function (/*string*/selectid,/*json object*/json) {
Select.clear (Selectid);
Select.add (Selectid, JSON);
};
This method is the same as create, but only on the original basis for the Append
Select.add = function (/*string*/selectid,/*json object*/json) {
try {
if (!json.options) return;
for (var i = 0; i < json.options.length i + +) {
Select.addoption (Selectid,json.options[i].value,json.options[i].text);
}
catch (ex) {
Base.alert (' Set Select Error: The specified JSON object does not conform to the resolution requirements of the Select Object! ');
}
};
Create a options and return
Select.createoption = function (/*string*/value,/*string*/text) {
var opt = document.createelement (' option ');
Opt.setattribute (' value ', value);
opt.innerhtml = text;
return opt;
};
Adds an option to the specified select and returns the current option object
Select.addoption = function (/*string*/selectid,/*string*/value,/*string*/text) {
var opt = select.createoption (value, text);
$ (Selectid). appendchild (opt);
return opt;
};
Gets the currently selected options object for the specified select, and returns an array if multiple selections are selected.
select.getselected = function (/*string*/selectid) {
var SLT = $ (Selectid);
if (!SLT) return null;
if (slt.type.toLowerCase () = = "Select-multiple") {
var len = Select.len (Selectid);
var result = [];
for (var i = 0; i < len; i + +) {
if (slt.options[i].selected) Result.push (Slt.options[i]);
}
return result.length > 1? Result: (Result.length = = 0 Null:result[0]);
} else {
var index = $ (selectid). SelectedIndex;