Change the options array of a select list

前端 未结 5 1315
青春惊慌失措
青春惊慌失措 2020-12-03 10:29

Is there a way to change the options array of an html select list using javascript or mootools?

I need to replace the entire options set with a new one. In my ajax

5条回答
  •  一个人的身影
    2020-12-03 10:30

    Manipulate the DOM using remove and add on the select object. You can see http://www.w3schools.com/jsref/dom_obj_select.asp for more info.

    For add new options to some select element I have write the following code:

    /**
        Adds an option to a select(HTML) element.
        @param {HTMLElement} select_element The select eletement.
        @param {string} option_str The text of the option.
        @param {Object} [option_attr] The options to be copied into the option element created.
        @returns {HTMLElement} The option element created.
    */
    function addOptionStrToSelectElement(select_element, option_str, option_attr){
        if (!option_attr) option_attr = {};
        var doc = select_element.ownerDocument;
        var opt = doc.createElement("option");
        opt.text = option_str;
        for (var prop in option_attr){
            if (option_attr.hasOwnProperty(prop)){
                opt[prop] = option_attr[prop];
            }
        }
        doc = null;
        if (select_element.add.length === 2){
            select_element.add(opt, null); // standards compliant
        } else{
            select_element.add(opt); // IE only
        }
        return opt;
    }
    

提交回复
热议问题