set option "selected" attribute from dynamic created option

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

var opt = $("option[val=ID]"),
    html = $("<div>").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: <option value="ID">Indonesia</option>.

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/


Instead of modifying the HTML itself, you should just set the value you want from the relative option element:

$(function() {
    $("#country").val("ID");
});

In this case "ID" is the value of the option "Indonesia"


You're overthinking it:

var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;