set option “selected” attribute from dynamic created option

后端 未结 17 1717
时光说笑
时光说笑 2020-11-30 20:01

I have a dynamically created select option using a javascript function. the select object is


<         


        
17条回答
  •  旧巷少年郎
    2020-11-30 20:56

    Good question. You will need to modify the HTML itself rather than rely on DOM properties.

    var opt = $("option[val=ID]"),
        html = $("
    ").append(opt.clone()).html(); html = html.replace(/\>/, ' selected="selected">'); opt.replaceWith(html);

    The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: .

    It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.

    I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/

提交回复
热议问题