开发者

How to add a select list with options to a DOM element using jQuery

Today I try to make a dynamic dropdownlist using jQuery. 开发者_JS百科I only provide one select list on the page at started. After usser selecting a option, if the selected category has sub categories, one new select list will be added next to the original select list by jQuery.

But I don't know how to implement my idea. How to add a select list and add options to the select list, finally add it to page using jQuery.

My codes are below:

$.getJSON(
    '/Work/Content/Categories/' + currentValue,
    '{Id:Name}',
    function (data) {
        if (data.length > 0) {
            $current.append('<select></select>');
            $selectList = $('fieldset > select:last');
            $.each(data, function (index, value) {
                var option = new Option(value.Id, value.Name);
                if ($.browser.msie)
                    $selectList.add(option);
                else
                    $selectList.add(option, null);
            });
        }
    }
);

Thanks every body.


First off, do you need to use Ajax to do this? Can you just load all of the selects on the page initially and only show/enable the ones that are needed appropriately? If there are TONs of selects this may not be the best option, but otherwise it is a superior solution to an Ajax one.

If you really want to use Ajax, there is no need to do this with JSON. Why not just have the page that you are getting the select data from print out an actual select box on its own and just append that to the DOM?


I would recommend rather than trying to dynamically add stuff like this to the page, instead have it all setup and just hide and show the select lists depending on the input.

Adding new elements to a page is very costly, and the code to do something like this is going to be very complex, however it would be quite easy to use the CSS property display: none and display: block instead (display: none will hide an element, while display: block will show it).

This is the methodology that most jQuery plugins, including jQuery UI tend to use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜