0

so essentially I was given an array of countries and I must first generate a loop into a drop-down list that displays the country names.

Second, the value attributes for each item in the list should be the country code

Then I must add an event handler for the drop-down lists change event so that when a country is selected it will display the capital of the city.

I've tried playing around with loops and change event handlers but I can't seem to figure it out.

Any help is appreciated thank you.

I know it's a mess but I'm having a tough time.

var countries = [{
    code: "AR",
    name: "Argentina",
    capital: "Buenos Aires"
  },
  {
    code: "AT",
    name: "Austria",
    capital: "Vienna"
  },
  {
    code: "BE",
    name: "Belgium",
    capital: "Brussels"
  },
  {
    code: "CA",
    name: "Canada",
    capital: "Ottawa"
  }
];

var select = document.getElementById('selectCountries');

for (var i = 0; i < countries.length; i++) {
  var optco = countries[i];
  var opt = document.createElement('options');
  opt.textContent = optco;
  opt.value = optco;
  select.appendChild(opt);

  // loop for grabbing each country name and displaying it in the drop-down
}


document.getElementById('countries').innerHTML

// use an onchange event
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Array Countries</title>
</head>

<body style="background-color: powderblue">
  <h1> Country Info Guide </h1>
  <p> Please Select a Country for More Information</p>
  <form method=get action=whatever.php>
    Select a country:
    <select id="selectCountries" onchange="GetCapital(this)">
    </select>
    <div>
      <p>
      </p>
    </div>
  </form>
</body>
</html>

4 Answers 4

1

You where close.

  • .createElement('options') is option not options

  • countries[i] in loop is whole one object from array with all data for one country. SO you need to append just parts of it with .name and .code:

    opt.textContent = optco.name;
    opt.value = optco.code;
    
  • Use this as function on change for example:

...

function GetCapital(event) {
  let res = countries.filter(e => e.code == event.value).map(e=>e.capital).toString()
  document.getElementById('result').innerHTML = res
}

event is select element, event.value is selected value (witch you appended before) on change.

Then you filter your initial array of countries to extract the one with code you selected from drop down.

var countries = [{
    code: "AR",
    name: "Argentina",
    capital: "Buenos Aires"
  },
  {
    code: "AT",
    name: "Austria",
    capital: "Vienna"
  },
  {
    code: "BE",
    name: "Belgium",
    capital: "Brussels"
  },
  {
    code: "CA",
    name: "Canada",
    capital: "Ottawa"
  }
];

var select = document.getElementById('selectCountries');

for (var i = 0; i < countries.length; i++) {
  var optco = countries[i];
  var opt = document.createElement('option');
  opt.textContent = optco.name;
  opt.value = optco.code;
  select.appendChild(opt);

  // loop for grabbing each country name and displaying it in the drop-down
}

function GetCapital(event) {
  let res = countries.filter(e => e.code == event.value).map(e=>e.capital).toString()
  document.getElementById('result').innerHTML = res
}


// use an onchange event
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Array Countries</title>
</head>

<body style="background-color: powderblue">
  <h1> Country Info Guide </h1>
  <p> Please Select a Country for More Information</p>
  <form method=get action=whatever.php>
    Select a country:
    <select id="selectCountries" onchange="GetCapital(this)">
    </select>
    <div id="result">
      <p>
      </p>
    </div>
  </form>
</body>

</html>

Sign up to request clarification or add additional context in comments.

1 Comment

@MisterJojo Thats cool and all but I fixed OP's attempt. But to be also honest, I always forgot about option constructor anyway.
1

this way:

1 - Select elements have native methods for adding options (no needs of select.appendChild(opt) )
use HTMLSelect​Element​.add(item[, before])

2 - Options element have a constuctor (no needs of document.createElement('option'))
use new Option(text, value, defaultSelected, selected)
to directly set options attributes in one instruction

const countries = 
  [ { code: 'AR', name: 'Argentina', capital: 'Buenos Aires' } 
  , { code: 'AT', name: 'Austria',   capital: 'Vienna'       } 
  , { code: 'BE', name: 'Belgium',   capital: 'Brussels'     } 
  , { code: 'CA', name: 'Canada',    capital: 'Ottawa'       } 
  ] 

const myForm = document.forms['my-form']

countries.forEach(c => myForm.selectCountries.add( new Option(c.name,c.code )))

myForm.selectCountries.oninput = e =>
  {
  let cod = myForm.selectCountries.value
  console.clear()
  console.log( cod , '=>', JSON.stringify( countries.find(x=>x.code===cod)))
  }
body  {
  background-color: powderblue;
  }
  <h1> Country Info Guide </h1>

  <p> Please Select a Country for More Information</p>
  
  <form method=get action=whatever.php  id="my-form">
    Select a country:

    <select name="selectCountries"></select>
  </form>

Comments

0

You can do it this way.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Array Countries</title>
</head>
<body style="background-color: powderblue">
    <h1> Country Info Guide </h1>   
    <p> Please Select a Country for More Information</p>
    <form method="get" action="whatever.php">
        Select a country:
        <!-- here we use onfocus event -->
        <select name="countries" id="selectCountries" onfocus="getCountries()"></select>
    </form>
    <script>
        // const for JSON array
        const countries = [{ code: "AR", name: "Argentina", capital: "Buenos Aires" },
        { code: "AT", name: "Austria", capital: "Vienna" },
        { code: "BE", name: "Belgium", capital: "Brussels" },
        { code: "CA", name: "Canada", capital: "Ottawa" }];

        // use let instead of var
        let select = document.getElementById('selectCountries');

        function getCountries() {
            // loop to append data only if select is empty
            if(!select.innerHTML){
                // loop for grabbing each country name and displaying it in the drop-down
                for (let i=0; i < countries.length; i++){
                    // read more on how to use object destructuring
                    let { name } = countries[i];
                    // <option value="value">innerHTML</option>
                    let option = document.createElement('OPTION');
                    option.value = name;
                    option.innerHTML = name;
                    // append current option to select
                    select.appendChild(option);  
                }
            }
        }
    </script>
</body>
</html>

Comments

0

Your array is an array of objects, so you can iterate over the objects using a for in loop. Then an eventListener for the change, use the event.target to get the value and match it with the array[key].capital and display it to the div on the page with display.textConent.

NOTE: We use a disabled option and select it by default as we are using change for the event listener, this way it changes if the user selects the first option, Argentina

const countries = [{
    code: "AR",
    name: "Argentina",
    capital: "Buenos Aires"
  },
  {
    code: "AT",
    name: "Austria",
    capital: "Vienna"
  },
  {
    code: "BE",
    name: "Belgium",
    capital: "Brussels"
  },
  {
    code: "CA",
    name: "Canada",
    capital: "Ottawa"
  }
];
const selectCountries = document.getElementById('selectCountries')
const display = document.getElementById('display')

function createSel(arr) {
  let code, name, capital = ''
  for (let key in arr) {
    let opt = document.createElement('option')
    code = arr[key].code
    name = arr[key].name
    capital = arr[key].capital
    opt.value = code
    opt.textContent = name
    selectCountries.append(opt)
  }
}

createSel(countries)

function findCapital(e){
  for (let key in countries) {
    if (countries[key].code === e.target.value) {
      display.textContent = `${countries[key].name}'s capital is ${countries[key].capital}`
    }
  }
}

selectCountries.addEventListener('change', findCapital)
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Array Countries</title>
</head>

<body style="background-color: powderblue">

  <h1> Country Info Guide </h1>

  <p> Please Select a Country for More Information</p>


  <select id="selectCountries">
    <option selected disabled>Select a country Below:</option>
  </select>
  <div id="display"></div>

1 Comment

6 one, half a dozen the other

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.