Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

select option in js dynamically

const countries = {
  AF: 'Afghanistan',
  AL: 'Albania',
  HR: 'Croatia',
  ID: 'Indonesia',     // <<< make this one defaultSelected
  ZW: 'Zimbabwe',
};

const EL_country = document.querySelector('#country');
const DF_options = document.createDocumentFragment();

Object.keys(countries).forEach(key => {
  const isIndonesia = key === 'ID';  // Boolean
  DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))
});

EL_country.appendChild(DF_options);

document.forms[0].reset(); // "Indonesia" is still selected
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #select #option #js #dynamically
ADD COMMENT
Topic
Name
6+6 =