Dynamically adding and selecting a menuitem in XUL
I'm using a Javascript object containing a list of phone codes to generate a dropdown menu in XUL. My object has this form:
var CountryCodes = {
"Afghanistan":"+93",
"Albania":"+355",
"Algeria":"+213"
}
The code for populating the menupopup looks like this:
var docfrag = document.createDocumentFragment();
for( var country in CountryCodes ) {
var this_country = document.createElementNS(XUL_NS,'menuitem');
this_country.setAttribute( 'label', country );
this_country.setAttribute( 'value', CountryCodes[ country ] );
docfrag.appendChild( this_country );
}
$('countryCodePopup').appendChild( docfrag );
$('countryCode').setAttribute( 'selectedIndex', 0 );
and my XUL looks like this:
<menulist id="countryCode">
<menupopup id="countryCodePopup"></menupopup>
</menulist>
However, when I run it on the page, the menuitem gets created properly, but the first element of the menu doesn't get selected. I tried to s开发者_运维百科et a selected attribute on one of the fields, but the result is the same. What am I missing here?
Thanks! Luka
Update: As it turns out, I was setting selectedIndex incorrectly. It should have been done like so: $('countryCode').selectedIndex = 10;
Try like this:
document.getElementById("countryCode").selectedIndex = 10;
For reference, please check this: https://developer.mozilla.org/en/XUL_Tutorial/Manipulating_Lists
精彩评论